您的位置:首页 > 其它

[Leetcode] 422. Valid Word Square 解题报告

2017-10-30 16:13 253 查看
题目

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: