504 / 504 个通过测试用例
状态:通过
执行用时:9 ms
内存消耗:42.9 MB
提交时间:6 月,3 周之前

import java.util.HashSet;
import java.util.Set;

class Solution {
    public boolean isValidSudoku(char[][] board) {
        StringBuilder str = new StringBuilder();
        Set<Character> set = new HashSet<>();
        int split = 0;//记录 . 负号的个数
        //检测行是否有重复
        for (int j = 0; j < 9; j++) {

            for (int i = 0; i < 9; i++) {
                if (board[j][i] == '.') {
                    split++;
                }else {set.add(board[j][i]);}
            }
            if (set.size() < 9 - split){
                System.out.println("行重复了");
                return false;
            }
                split = 0;
                set.clear();
        }
        //检测列有重复
        for (int i = 0; i <9 ; i++) {

            for (int j = 0; j < 9; j++) {
                if (board[j][i] == '.') {
                    split++;
                }else {set.add(board[j][i]);}
            }
            if (set.size() < 9 - split){
                System.out.println("列重复了");
                return false;
            }
            split = 0;
            set.clear();
        }
        //检测九宫格
        int ni = 3;
        int nj = 3;
        int temp = 0;
        int tempi = 0;
        set.clear();
        split = 0;
        for (int i = 0; i < 3; i++) {
        for (; tempi <ni ; tempi++) {
            for (int j = 0+temp; j < nj+temp; j++) {
                if (board[tempi][j] == '.')
                    split++;
                else
                    set.add(board[tempi][j]);
                if ((j+1) % 3 == 0 && (tempi+1) %3 ==0) {
                    if (set.size() < 9 - split){
                        System.out.println("九宫格重复");
                        return false;
                    }
                    split = 0;
                    set.clear();
                        break;
                }
             }
             if ((tempi+1) == 3){
                if (temp < 6) {
                    temp += 3;
                    tempi = -1;
                }
             }
             if ((tempi+1) == 6){
                 if (temp < 6) {
                     temp += 3;
                     tempi = 2;
                 }
             }
            if ((tempi+1) == 9){
                if (temp < 6) {
                    temp += 3;
                    tempi = 5;
                }
            }
         }
            ni += 3;
            temp = 0;
        }

        return true;
    }
}
Last modification:May 5th, 2020 at 11:13 pm
如果觉得我的文章对你有用,请随意赞赏