-
Notifications
You must be signed in to change notification settings - Fork 154
/
valid-word-square.js
93 lines (90 loc) · 1.94 KB
/
valid-word-square.js
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
/**
* Valid Word Square
*
* 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.
*
* 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.
*/
/**
* @param {string[]} words
* @return {boolean}
*/
const validWordSquare = words => {
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words[i].length; j++) {
// (j >= words.length) means the the number of rows is too small
// (i >= words[j].length) means the word at j-th row is too short
if (j >= words.length || i >= words[j].length || words[i][j] !== words[j][i]) {
return false;
}
}
}
return true;
};
export { validWordSquare };