[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 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         stack<char> st;
 7         
 8         for(int i = 0; i < s.size(); i++)
 9             if (s[i] == ')' || s[i] == ']' || s[i] == '}')
10             {
11                 if (st.empty())
12                     return false;
13                 else
14                 {
15                     char c = st.top();
16                     st.pop();
17                     if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}'))
18                         return false;
19                 }
20             }
21             else
22                 st.push(s[i]);
23                 
24         return st.empty();
25     }
26 };
posted @ 2012-11-18 11:54  chkkch  阅读(4047)  评论(0编辑  收藏  举报