422. Valid Word Square

  • 36.1%

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:

  1. The number of words given is at least 1 and does not exceed 500.
  2. Word length will be at least 1 and does not exceed 500.
  3. Each word contains only lowercase English alphabet a-z.

java

34ms, , October 16, 2016

https://discuss.leetcode.com/topic/63387/java-ac-solution-easy-to-understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public boolean validWordSquare(List<String> words) {
if(words == null || words.size() == 0){
return true;
}

int n = words.size();
for(int i=0; i<n; i++)
for(int j=0; j<words.get(i).length(); j++)
if(n <= j || words.get(j).length()<=i || words.get(j).charAt(i) != words.get(i).charAt(j))
return false;

return true;
}
}

cpp

23ms, , October 16, 2016

question:https://leetcode.com/contest/9/problems/valid-word-square/

https://discuss.leetcode.com/topic/63377/accepted-concise-c-solution

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
bool validWordSquare(vector<string>& words) {
for(int i=0; i< words.size(); ++i)
for(int j=0; j<words[i].size(); ++j)
if(words.size() <= j || words[j].size() <= i || words[j][i] != words[i][j])
return false;
return true;
}
};

python

129ms, , October 16, 2016

https://discuss.leetcode.com/topic/63377/accepted-concise-c-solution

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def validWordSquare(self, words):
"""
:type words: List[str]
:rtype: bool
"""
for i in range(len(words)):
for j in range(len(words[i])):
if len(words) <= j or len(words[j]) <= i or words[i][j] != words[j][i]:
return False
return True
谢谢你,可爱的朋友。