1
class Solution {
2
public boolean validTicTacToe(String[] board) {
3
// cnt number of X and O
4
int x = cntNumber('X', board);
5
// this check can be omitted, it can be covered in the second number check.
6
if (x > 5) {
7
return false;
8
}
9
int o = cntNumber('O', board);
10
if (x < o || x > o + 1) {
11
return false;
12
}
13
// if(x <3 ) true, no need to see winning
14
if (o >= 3) {
15
// if x has won, but game doesnt stop
16
if (x == o && hasWon('X', board)) {
17
return false;
18
}
19
// if o has won, but game doesnt stop
20
if (x > o && hasWon('O', board)) {
21
return false;
22
}
23
}
24
return true;
25
}
26

27
private int cntNumber(char target, String[] board) {
28
int res = 0;
29
for (int i = 0; i < 3; i++) {
30
for (int j = 0; j < 3; j++) {
31
if (target == board[i].charAt(j)) {
32
res++;
33
}
34
}
35
}
36
return res;
37
}
38

39
private boolean hasWon(char target, String[] board) {
40
String toWin = Character.toString(target).repeat(3);
41
for (int i = 0; i < 3; i++) {
42
if (board[i].equals(toWin)) {
43
return true;
44
}
45
}
46
for (int j = 0; j < 3; j++) {
47
boolean col = true;
48
for (int i = 0; i < 3; i++) {
49
col = col && target == board[i].charAt(j);
50
if (!col) {
51
break;
52
}
53
}
54
if (col) {
55
return true;
56
}
57
}
58
// check diagonal. If center is not target, not possible to form diag win.
59
if (target != board[1].charAt(1)) {
60
return false;
61
}
62

63
boolean diagonal1 = target == board[0].charAt(0);
64
// only proceed if the first letter match. Otherwise might get false positive
65
if (diagonal1) {
66
if (target == board[2].charAt(2)) {
67
return true;
68
}
69
}
70

71
boolean diagonal2 = target == board[0].charAt(2);
72
if (diagonal2) {
73
if (target == board[2].charAt(0)) {
74
return true;
75
}
76
}
77
return false;
78
}
79
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0