-
Notifications
You must be signed in to change notification settings - Fork 0
/
Valid Parentheses.js
42 lines (40 loc) · 1.22 KB
/
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
/*Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
if(s.length%2 != 0)
return false
if(s[0]){
var stack = []
var a = s.split('')
for(var i=0; i<a.length; i++){
if(a[i] == '{' || a[i] == '[' || a[i] == '(')
stack.push(a[i])
else{
switch(a[i]){
case '}':
if(stack.pop() != '{')
return false
else
break
case ']':
if(stack.pop() != '[')
return false
else
break
case ')':
if(stack.pop() != '(')
return false
else
break
}
}
}
if(stack[0])
return false
}
return true
};