Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid word square if thekthrow and column read the exact same string, where 0 ≤k< max(numRows, numColumns).
Note:
- The number of words given is at least 1 and does not exceed 500.
- Word length will be at least 1 and does not exceed 500.
- Each word contains only lowercase English alphabet
a-z
.
class Solution {
public boolean validWordSquare(List<String> words) {
if(words == null || words.size() == 0)
return true;
int n = words.size();
if(words.get(0).length() != n)
return false;
char[][] t = new char[n][n];
for(int i = 0; i < n; i++) {
if(words.get(i).length() > n)
return false;
for(int j = 0; j < n; j++) {
if(j < words.get(i).length()) {
t[i][j] = words.get(i).charAt(j);
} else {
t[i][j] = '\0';
}
}
}
for(int i = 0; i < n; i++) {
int j = i;
int k = i;
while(j < n && k < t[i].length) {
System.out.println(t[j][i]);
if(t[j][i] != t[i][k])
return false;
j++;
k++;
}
if(j != k)
return false;
}
return true;
}
}