0422. Valid Word Square
Previous0421. Maximum XOR of Two Numbers in an ArrayNext0423. Reconstruct Original Digits from English
Last updated
Last updated
**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.**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.**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.class Solution {
public boolean validWordSquare(List<String> words) {
// edge cases
if (words == null || words.size() == 0 || words.size() != words.get(0).length()) return false;
for (int i = 0; i < words.size(); i++) {
String ver = readVertical(words, i);
if (!words.get(i).equals(ver)) return false;
}
return true;
}
private String readVertical(List<String> words, int col) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.size(); i++) {
if (col < words.get(i).length())
sb.append(words.get(i).charAt(col));
}
return sb.toString();
}
}