forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 14
/
20 Valid Parentheses.js
52 lines (43 loc) · 1.24 KB
/
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
47
48
49
50
51
52
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
var stack = [];
var index = 0;
while(index < s.length){
var c = s[index];
if(c === "(" || c === "[" || c === "{"){
stack.push(c);
} else {
var oldC = stack.pop();
if(oldC === '(' && c !== ')'){
return false;
} else if(oldC === '[' && c !== ']'){
return false;
} else if(oldC === '{' && c !== '}'){
return false;
} else if(oldC === undefined) {
return false;
}
}
index++;
}
return stack.length === 0;
};
// second attempt
var isValid = function(s) {
var stack = [];
for(var i = 0; i < s.length; i++) {
var chr = s[i];
if(chr === '(' || chr === '{' || chr === '[') {
stack.push(chr);
} else if(chr === ')' || chr === '}' || chr === ']') {
var top = stack.pop();
if(!top || (top === '(' && chr !== ')') || (top === '{' && chr !== '}') || (top === '[' && chr !== ']')) {
return false;
}
}
}
return stack.length === 0;
};