【HashMap】2352. 相等行列对

2352. 相等行列对

解题思路

  • 使用哈希容器
  • 遍历grid数组 将每一行的字符全部转换为StringBuilde对象 然后存入map中
  • 遍历每一列 将其转换为字符串 然后查找Map中是否存在 如果存在 统计
class Solution {
    public int equalPairs(int[][] grid) {
        // 哈希容器
        Map<String,Integer> map = new HashMap<>();

        // 创建StringBuilder
        StringBuilder sb = new StringBuilder();

        // 遍历grid数组
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid.length; j++){
                // 将每一行的字符全部转换为StringBuilder对象 然后存入map
                sb.append(grid[i][j]).append('%');
                // 针对每一个字符都需要%进行隔开

            }

            // 将字符串存入Map
            map.put(sb.toString(),map.getOrDefault(sb.toString(),0) + 1);
            // 清空builder中的缓存
            sb.setLength(0);
        }

        // 遍历每一列 将其转换为字符串 然后查找Map中是否存在
        int count = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid.length; j++){
                sb.append(grid[j][i]).append("%");
            }

            if(map.containsKey(sb.toString())){
                // 如果存在 count++;
                count += map.get(sb.toString());
            }

            sb.setLength(0);
        }

        return count;
        
    }
}

你可能感兴趣的:(#,Leetcode,spring,boot,算法)