20. Valid Parentheses

20. Valid Parentheses

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.

 1 /**
 2  * @param {string} s
 3  * @return {boolean}
 4  */
 5 var isValid = function(s) {
 6     
 7     //数据结构里关于括弧匹配的问题往往用堆栈解决
 8     //如果是出现左括弧,我们就压栈,
 9     //如果是右括弧,我们就pop出来一个,看看是不是匹配,不匹配就是不合格的
10     
11     var slen = s.length;
12     var stack = [];
13      
14     function check(s,p){
15         
16         switch(s){
17                 
18             case '(':
19                 return p !=')';
20             case '{':
21                 return p !='}';
22             case '[':
23                 return p !=']';
24         }
25     }
26     
27     
28     for(var i = 0;i < slen;i++){
29         
30         var p = s.charAt(i);
31                 
32         switch(p){
33                 
34             case '}':
35             case ')':
36             case ']':
37                if(!stack.length){
38                     return false;
39                 }
40                 var pop = stack.pop();
41                 var res = check(pop,p);
42                 if(res){
43                     return !res;
44                 }
45                 break;
46             default:
47                 stack.push(p);
48                 
49         }
50         
51     }
52     
53     //全都匹配完了,看看是不是stack还有数据,有就是false
54     if(stack.length){
55         return false;
56     }
57     
58     return true;
59     
60     
61 };

 

posted @ 2017-10-12 15:37  hdu胡恩超  阅读(164)  评论(0编辑  收藏  举报