422. Valid Word Square

compare by len

T: O(n*L), n is words list size, L is word len

S: O(1)

class Solution {
    public boolean validWordSquare(List<String> words) {
        int n = words.size();
        
        for (int i = 0; i < n; i++) { // n is col len
            String word = words.get(i);
            for (int j = 0; j < word.length(); j++) {
                // j >= n, word is too long (in row length, so n can't compare with row len)
                // words.get(j).length() <= i, col len is shorter than i
                if (j >= n || 
                    words.get(j).length() <= i ||
                    word.charAt(j) != words.get(j).charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
}

filled with empty in matrix, then compare if (w[i][j] != w[j][i])

T: O(n^2), n is Square side length

S: O(n^2)

class Solution {
    public boolean validWordSquare(List<String> words) {
        // check entire size is legal, max word size should equal to words list size
        int len = 0;
        for (String w : words) {
            len = Math.max(w.length(), len);
        }
        if (words.size() != len) {
            return false;
        }
        
        char w[][] = new char[len][len];
        for (int i = 0; i < len; i++) {
            StringBuilder str = new StringBuilder(words.get(i));
            int spaces = len - str.length();
            
            // fill out the empty to make all words in the same length
            for (int s = 0; s < spaces; s++) { // str length will change, so cant write in loop
                str.append(" ");    
            }
            w[i] = str.toString().toCharArray();
        }
        
        // compare w(row,col) == w(col, row)
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if (w[i][j] != w[j][i]) {
                    return false;
                }
            }
        }
        return true;
    }
}

Last updated