-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.valid-parentheses.js
46 lines (43 loc) · 971 Bytes
/
20.valid-parentheses.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
/*
* @lc app=leetcode id=20 lang=javascript
*
* [20] Valid Parentheses
*/
// @lc code=start
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
if (s.length === '') return true
if (s.length === 1) return false
let stack = []
for (let i = 0; i < s.length; i++) {
if ('([{'.indexOf(s[i]) > -1) {
stack.push(s[i])
} else {
let matchMap = {
')': '(',
']': '[',
'}': '{'
}
let toMatch = stack.pop()
if (toMatch !== matchMap[s[i]]) return false
}
}
return stack.length === 0
}
// var isValid = function(s) {
// let stack = []
// for (let i = 0; i < s.length; i++) {
// if (s[i] === '(') stack.push(')')
// else if (s[i] === '{') stack.push('}')
// else if (s[i] === '[') stack.push(']')
// else if (stack.length === 0 || stack.pop() !== s[i]) return false
// }
// return stack.length === 0
// }
// @lc code=end
module.exports = {
isValid
}