题目:
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.
思路:
一道相对简单的题目,唯一需要注意的是边界条件,以及判断字符串长度方面的细节。算法的时间复杂度是O(n^2)。
代码:
class Solution {
public:
bool validWordSquare(vector<string>& words) {
int row_num = words.size();
for(int i = 0; i < row_num; ++i) {
if(words[i].length() > row_num) {
return false;
}
for(int j = i + 1; j < row_num; ++j) {
if(j < words[i].length()) { // first part
if(words[j].size() < i + 1 || words[j][i] != words[i][j]) {
return false;
}
}
else { // j >= words[i].length()
if(words[j].size() >= i + 1) {
return false;
}
}
}
}
return true;
}
};
本文介绍了一种算法,用于检查一系列单词是否构成有效的单词方阵。有效单词方阵是指每个单词的第 k 个字符与第 k 行的第 k 个单词相同。文章通过实例详细解释了判断过程,并提供了一个 C++ 实现方案。
396

被折叠的 条评论
为什么被折叠?



