有效的单词方块
题目
Given a sequence of words, check whether it forms a valid word square.
A sequence of words forms a valid word square if the kth row 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.
Example 1:
Input: [ “abcd”, “bnrt”, “crmy”, “dtye” ]
Output: true
Explanation: The first row and first column both read “abcd”. The
second row and second column both read “bnrt”. The third row and third
column both read “crmy”. The fourth row and fourth column both read
“dtye”.
Therefore, it is a valid word square.
Example 2:
Input: [ “abcd”, “bnrt”, “crm”, “dt” ]
Output: true
Explanation: The first row and first column both read “abcd”. The
second row and second column both read “bnrt”. The third row and third
column both read “crm”. The fourth row and fourth column both read
“dt”.
Therefore, it is a valid word square.
Example 3:
Input: [ “ball”, “area”, “read”, “lady” ]
Output: false
Explanation: The third row reads “read” while the third column reads
“lead”. Therefore, it is NOT a valid word square.
给定一个单词序列,检测它是否构成一个有效的单词正方形.
如果第k行和第k列读取完全相同的字符串,其中0<=k<max(numRows,numColumns),则单词序列形成一个有效的单词平方.
注意:
-
给出的单词数置为1 ,且不超过500.
-
单词长度将至少为1,且不超过500.
-
每个单词只包含小写英文字母a-z
示例1:
输入:[" abcd ", " bnrt ", " crmy ", " dtye "]
输出:true
说明:第一行和第一列都读“abcd”。第二行和第二列都读“bnrt”。第三行和第三行专栏都是“crmy”。第四行和第四列都读“dtye”。
因此,它是一个有效的字平方。
示例2:
输入:[" abcd ", " bnrt ", " crm ", " dt "]
输出:true
说明:第一行和第一列都读“abcd”。第二行和第二列都读“bnrt”。第三行和第三行专栏都是“crm”。第四行和第四列都读“dt”。
因此,它是一个有效的字平方。
示例3:
输入:[" ball ", " area ", " read ", " lady "]
输出:false
说明:第三行读取“read”,而第三列读取“lead”。因此,它不是一个有效的字平方。
思路
这道题主要考察是对两个边界条件的处理.一种情况是[" abcdc", " bnrt ", " crm ", " dt "].一种情况是[" abcd", " bnrt", " crm", " dtc"]
只要依次比较不同层次上的字符就可以了.
代码
public class Solution {
public boolean validWordSquare(List<String> words) {
for (int i = 0; i < words.size(); i++) {
String word = words.get(i);
for (int j = 0; j < word.length(); j++) {
if (words.size() < j+1 || words.get(j).length() < i+1 || word.charAt(j) != words.get(j).charAt(i)){
return false;
}
}
}
return true;
}
}
网友评论