leetcode题解: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)括号可嵌套,如{[()]}

实现:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         if(s.empty()) return false;//空字符串,false
 5         int len=strlen(s.c_str());
 6         if(len==1) return false;//只有一个字符,false
 7         char pre;
 8         stack<char> char_stack;
 9         for(int i=0;i<len;i++)
10         {
11            if(isPop(s[i])) //该出栈顶元素
12            {
13                if(!char_stack.empty())
14                {
15                    pre=char_stack.top();//取栈顶元素、并出栈
16                    char_stack.pop();
17                    if(!isChar(pre,s[i]))//是否匹配
18                       return false;
19                }
20                else return false;
21            }
22            else //入栈
23            {
24                char_stack.push(s[i]);
25            }
26         }
27        return char_stack.empty();//栈空true,否则false
28     }
29 private:
30     bool isPop(char t) //判断是否是)} ]符号,是则出栈栈顶元素
31     {
32         if(t==')'||t=='}'||t==']')
33            return true;
34         else 
35            return false;
36     }
37     bool isChar(char t1,char t2)//判断两字符t1,t2是否匹配
38     {
39         switch (t1)
40         {
41             case '(':
42             {
43                 if(t2==')') return true;
44                 else return false;
45                 break;
46             }
47             case '{':
48             {
49                 if(t2=='}') return true;
50                 else return false;
51                 break;
52             }
53             case '[':
54             {
55                 if(t2==']') return true;
56                 else return false;
57                 break;
58             }
59             default: 
60                 return false;
61         }
62     }
63 };

 

posted @ 2014-07-07 16:21  平凡的幸福...  阅读(301)  评论(0编辑  收藏  举报