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 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> stk;
 5         char c;
 6 
 7         for(int i=0;i<s.size();i++)
 8         {
 9             if(s[i]=='('||s[i]=='['||s[i]=='{')
10                 stk.push(s[i]);
11             else if(stk.empty())
12                 return false;
13             else if(s[i]==')')
14             {
15                 c=stk.top();
16                 if(c=='(')
17                     stk.pop();
18                 else
19                     return false;
20             }
21             else if(s[i]==']')
22             {
23                 c=stk.top();
24                 if(c=='[')
25                     stk.pop();
26                 else
27                     return false;
28             }
29             else if(s[i]=='}')
30             {
31                 c=stk.top();
32                 if(c=='{')
33                     stk.pop();
34                 else
35                     return false;
36             }
37         }
38 
39         if(stk.empty()==false) return false;
40 
41         return true;        
42     }
43 };

 

posted on 2015-05-22 08:42  黄瓜小肥皂  阅读(157)  评论(0编辑  收藏  举报