forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
42 lines (39 loc) · 1.18 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
private String[] board;
public boolean validTicTacToe(String[] board) {
this.board = board;
int x = count('X'), o = count('O');
if (x != o && x - 1 != o) {
return false;
}
if (win('X') && x - 1 != o) {
return false;
}
return !(win('O') && x != o);
}
private boolean win(char x) {
for (int i = 0; i < 3; ++i) {
if (board[i].charAt(0) == x && board[i].charAt(1) == x && board[i].charAt(2) == x) {
return true;
}
if (board[0].charAt(i) == x && board[1].charAt(i) == x && board[2].charAt(i) == x) {
return true;
}
}
if (board[0].charAt(0) == x && board[1].charAt(1) == x && board[2].charAt(2) == x) {
return true;
}
return board[0].charAt(2) == x && board[1].charAt(1) == x && board[2].charAt(0) == x;
}
private int count(char x) {
int cnt = 0;
for (var row : board) {
for (var c : row.toCharArray()) {
if (c == x) {
++cnt;
}
}
}
return cnt;
}
}