Uber 高频题,细节实现,没什么太多可说的
注意检查3*3 square可能会比较难想
1 public boolean isValidSudoku(char[][] board) { 2 if (board == null || board.length == 0) { 3 return false; 4 } 5 //O(MN) time 6 //O(N) space 7 int n = board.length; 8 int m = board[0].length; 9 HashSet<Character> set = new HashSet(); 10 //Check rows 11 for (int i = 0; i < n; i++) { 12 for (int j = 0; j < m; j++) { 13 if (board[i][j] != ‘.‘) { 14 if (set.contains(board[i][j])) { 15 //System.out.println("Row false " + board[i][j]); 16 return false; 17 } 18 set.add(board[i][j]); 19 } 20 } 21 set.clear(); 22 } 23 set.clear(); 24 //Check columns 25 for (int i = 0; i < m; i++) { 26 for (int j = 0; j < n; j++) { 27 if (board[j][i] != ‘.‘) { 28 if (set.contains(board[j][i])) { 29 //System.out.println("Column false " + board[j][i]); 30 return false; 31 } 32 set.add(board[j][i]); 33 } 34 } 35 set.clear(); 36 } 37 set.clear(); 38 //Check squares 39 for (int i = 0; i < n - 2; i += 3) { 40 for (int j = 0; j < m - 2; j += 3) { 41 for (int k = 0; k < 9; k ++) { 42 if (board[i + k / 3][j + k % 3] != ‘.‘) { 43 if (set.contains(board[i + k / 3][j + k % 3])) { 44 return false; 45 } 46 set.add(board[i + k / 3][j + k % 3]); 47 } 48 } 49 set.clear(); 50 } 51 } 52 return true; 53 }
时间: 2024-10-26 06:58:23