LeetCode 36

题目

36. 有效的数独 

思路

只能想到暴力遍历,然后使用数组来存储每个元素出现的次数;

去看了题解,使用三个数组分别统计每行、每列、每个3*3子区域中数字出现的次数,只需要遍历一遍,同时更新这三个数组就行了;

代码

public boolean isValidSudoku(char[][] board) {
        // 使用数组来记录每个数字出现的次数
        int[][] rows = new int[9][9];
        int[][] col = new int[9][9];
        int[][][] subboxs = new int[3][3][9];
        for(int i = 0; i < 9; i ++){
            for(int j = 0; j < 9; j++){
                if(board[i][j] != ('.')){
                    int nums = board[i][j] - '0' - 1; // 下标从0开始 也就是第0个下标记录1出现的次数
                    rows[i][nums] += 1;
                    col[j][nums] += 1;
                    subboxs[i/3][j/3][nums] += 1;
                    if(rows[i][nums] > 1 || col[j][nums] > 1 || subboxs[i/3][j/3][nums] > 1){
                        return false;
                    }
                }

            }
        }
        return true;
    }

题目

 

思路

将字符串转化为数字,使用hashmap记录每个字符的对应的数字; 

代码

public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        // 使用hash表来记录每个字符对应的数字 将字符串转化为数字
        HashMap<Character, Integer> smap = new HashMap<>();
        int scount = 0;
        HashMap<Character, Integer> tmap = new HashMap<>();
        int tcount = 0;
        for(int i = 0; i < s.length(); i++){
            if(!smap.containsKey(s.charAt(i))){
                smap.put(s.charAt(i), scount++);
            }
            if(!tmap.containsKey(t.charAt(i))){
                tmap.put(t.charAt(i), tcount++);
            }
            if(smap.get(s.charAt(i)) != tmap.get(t.charAt(i))){
                return false;
            }
        }
        return true;
    }

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值