-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path422.valid-word-square.cpp
More file actions
106 lines (105 loc) · 2.08 KB
/
422.valid-word-square.cpp
File metadata and controls
106 lines (105 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
* [422] Valid Word Square
*
* https://leetcode.com/problems/valid-word-square/description/
*
* algorithms
* Easy (36.28%)
* Total Accepted: 19.5K
* Total Submissions: 53.7K
* Testcase Example: '["abcd","bnrt","crmy","dtye"]'
*
* 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.
*
*
*/
class Solution {
public:
bool validWordSquare(vector<string>& words) {
bool isValid = true;
for (int i = 0; i < words.size() && isValid; ++i) {
for (int j = 0; j < words[i].size() && isValid; ++j) {
if (j >= words.size() || i >= words[j].size() ||
words[i][j] != words[j][i]) {
isValid = false;
}
}
}
return isValid;
}
};