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> st;
 5         int len = s.size();
 6         if (len % 2 != 0)
 7             return false;
 8         for (int i = 0; i < len; i++)
 9         {
10             if (s[i] == '(' || s[i] == '[' || s[i] == '{')
11                 st.push(s[i]);
12             else
13             {
14                 if (st.size() == 0)
15                     return false;
16                 else
17                 if (s[i] == m[st.top()])
18                 {
19                     //cout << s[i] << m[st.top()] << endl;
20                     st.pop();
21                     cout <<st.size()<<st.empty() << endl;
22                 }
23                 else
24                     return false;
25             }
26         }
27         if (st.size() == 0)
28             return true;
29         else
30             return false;
31     }
32     map<char, char> m;
33     Solution()
34     {
35         m.insert(pair<char, char>('(', ')'));
36         m.insert(pair<char, char>('[', ']'));
37         m.insert(pair<char, char>('{', '}'));
38     }
39 };

 

posted on 2017-07-06 09:52  无惧风云  阅读(116)  评论(0编辑  收藏  举报