October 05, 2019

794. Valid Tic-Tac-Toe State

794. Valid Tic-Tac-Toe State

Time = O(n), Space = O(n)

class Solution {
    public boolean validTicTacToe(String[] board) {
        int numOfX = 0;
        int numOfO = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i].charAt(j) == 'X') {
                    numOfX++;
                } else if (board[i].charAt(j) == 'O') {
                    numOfO++;
                }
            }
        }
        if (!(numOfX == numOfO || numOfX == numOfO + 1)) {
            return false;
        }
        if (numOfX == numOfO && win(board, 'X')) {
            return false;
        }
        if (numOfX == numOfO + 1 && win(board, 'O')) {
            return false;
        }
        return true;
    }
    
    private boolean win(String[] board, char c) {
        for (int i = 0; i < 3; i++) {
            if (board[i].charAt(0) == c && board[i].charAt(1) == c && board[i].charAt(2) == c) {
                return true;
            }
        }
        for (int j = 0; j < 3; j++) {
            if (board[0].charAt(j) == c && board[1].charAt(j) == c && board[2].charAt(j) == c) {
                return true;
            }
        }
        if (board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c) {
            return true;
        }
        if (board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c) {
            return true;
        }
        return false;
    }
}
comments powered by Disqus