My JAVA solution with HashSet


  • 0
    Q
    public class Solution {
        public boolean isValidSudoku(char[][] board) {
    		Set<Character> set = new HashSet<Character>();
    
    		//horizontals
    		for (int i=0;i<9;i++){
    			set.clear();
    			for (int j=0;j<9;j++){
    				char c = board[i][j];
    				if (c=='.'){
    				    continue;
    				}
    				if (set.contains(c)){
    					return false;
    				}
    				set.add(c);
    			}
    		}
    		
    		//verticals
    		for (int i=0;i<9;i++){
    			set.clear();
    			for (int j=0;j<9;j++){
    				char c = board[j][i];
    				if (c=='.'){
    				    continue;
    				}
    				if (set.contains(c)){
    					return false;
    				}
    				set.add(c);
    			}
    		}
    
            //3x3s
    		for (int n=0;n<3;n++){
    			for (int m=0;m<3;m++){
    				set.clear();
    				for (int i=n*3;i<n*3+3;i++){
    					for (int j=m*3;j<m*3+3;j++){
    						char c = board[i][j];
    						if (c=='.'){
    						    continue;
    						}
    						if (set.contains(c)){
    							return false;
    						}
    						set.add(c);
    					}
    				}
    			}
    		}
    		
    		return true;
        }
    }

  • 0
    W

    you don't really need hashset at this time. array is enough


  • 0
    Q

    Yes array would work, and is actually faster in the case of such small set


Log in to reply
 

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