My Java solution


  • 2
    A

    public class Solution {

    public boolean isValidSudoku(char[][] board) {
        HashSet<Character> set = new HashSet<Character>();
        //horizontal and vertical judging
        for (int i=0; i<9; i++) {
            set.clear();
            for (int j=0; j<9; j++) {
                char location = board[i][j];
                if (location == '.') continue;
                if (set.contains(location)) return false;
                set.add(location);
            }
        }
        for (int i=0; i<9; i++) {
            set.clear();
            for (int j=0; j<9; j++) {
                char location = board[j][i];
                if (location == '.') continue;
                if (set.contains(location)) return false;
                set.add(location);
            }
        }
        //3*3 judging
        for (int m=0; m<3; m++) {
            for (int n=0; n<3; n++) {
                set.clear();
    
                for (int i=m*3; i<m*3+3; i++) {
                    for (int j=n*3; j<n*3+3; j++) {
                        char location = board[i][j];
                        if (location == '.') continue;
                        if (set.contains(location)) return false;
                        set.add(location);
                    }
                }
            }
        }
        return true;
    }
    

    }


  • 0
    A

    The set.add(location) will return boolean result, which indicates whether the key already contained.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.