$$
\begin{bmatrix}
\colorbox{red} a & \colorbox{red} b & \colorbox{red} c & \colorbox{red} d \\
\colorbox{red} b & \colorbox{green} n & \colorbox{green} r & \colorbox{green} t \\
\colorbox{red} c & \colorbox{green} r & \colorbox{blue} m & \colorbox{blue} y \\
\colorbox{red} d & \colorbox{green} t & \colorbox{blue} y & \colorbox{violet} e
\end{bmatrix}
$$
1
2
3
4
5
6
7
8
Input: words = ["abcd","bnrt","crmy","dtye"]
Output: true
Explanation:
The 1st row and 1st column both read "abcd".
The 2nd row and 2nd column both read "bnrt".
The 3rd row and 3rd column both read "crmy".
The 4th row and 4th column both read "dtye".
Therefore, it is a valid word square.
Example 2:
$$
\begin{bmatrix}
a & b & c & d \\
b & n & r & t \\
c & r & m \\
d & t
\end{bmatrix}
$$
1
2
3
4
5
6
7
8
Input: words = ["abcd","bnrt","crm","dt"]
Output: true
Explanation:
The 1st row and 1st column both read "abcd".
The 2nd row and 2nd column both read "bnrt".
The 3rd row and 3rd column both read "crm".
The 4th row and 4th column both read "dt".
Therefore, it is a valid word square.
Example 3:
$$
\begin{bmatrix}
b & a & \colorbox{blue} l & l \\
a & r & \colorbox{blue} e & a \\
\colorbox{red} r & \colorbox{red} e & \colorbox{red} a & \colorbox{red} d \\
l & a & \colorbox{blue} d & y
\end{bmatrix}
$$
1
2
3
4
5
Input: words = ["ball","area","read","lady"]
Output: false
Explanation:
The 3rd row reads "read" while the 3rd column reads "lead".
Therefore, it is NOT a valid word square.
classSolution {
public:bool validWordSquare(vector<string>& words) {
int m = words.size();
for (int i =0; i < m; ++i) {
int n = words[i].size();
for (int j =0; j < n; ++j) {
if (j >= m || i >= words[j].size() || words[i][j] != words[j][i]) {
return false;
}
}
}
return true;
}
};
classSolution {
publicbooleanvalidWordSquare(List<String> words) {
int m = words.size();
for (int i = 0; i < m; ++i) {
int n = words.get(i).length();
for (int j = 0; j < n; ++j) {
if (j >= m || i >= words.get(j).length()) {
returnfalse;
}
if (words.get(i).charAt(j) != words.get(j).charAt(i)) {
returnfalse;
}
}
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defvalidWordSquare(self, words: List[str]) -> bool:
m = len(words)
n = max(len(w) for w in words)
if m != n:
returnFalsefor j in range(n):
if words[j] !="".join(w[j] for w in words if j < len(w)):
returnFalsereturnTrue
1
2
3
4
5
6
7
8
classSolution:
defvalidWordSquare(self, words: List[str]) -> bool:
m = len(words)
for i, w in enumerate(words):
for j, c in enumerate(w):
if j >= m or i >= len(words[j]) or c != words[j][i]:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
functionvalidWordSquare(words: string[]):boolean {
constm=words.length;
for (leti=0; i<m; ++i) {
constn=words[i].length;
for (letj=0; j<n; ++j) {
if (j>=m||i>=words[j].length||words[i][j] !==words[j][i]) {
returnfalse;
}
}
}
returntrue;
}