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)
Last updated
Was this helpful?