-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathE_ValidParentheses.js
42 lines (36 loc) · 966 Bytes
/
E_ValidParentheses.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.
*
* */
//tag stack
//done
//ac 134ms
function validParentheses(s){
//use js array, push, pop
//if "(" "{" "[", push, if ")" "}" "]" pop, the final array should be empty
var array = [];
for(var i =0; i< s.length; i++){
var curr = s.charAt(i);
if(curr === "(" || curr === "{" || curr === "[" ){
array.push(curr);
} else {
var peek = array.pop();
if((curr === ")" && peek ==="(")|| (curr === "}" && peek ==="{") || (curr === "]" && peek ==="[") ){
// array.pop();
} else {
array.push(peek); //push back and push in current
array.push(curr);
}
}
}
if(array.length != 0){
return false;
} else {
return true;
}
}
var str = "[{}][({})][][][]{}{}";
console.log(validParentheses(str));