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         if( s.empty() ) return true;
 5         stack<char> st;
 6         st.push('#');
 7         for(int i=0; i<s.length(); ++i)
 8             if( s[i] == '(' || s[i] == '{' || s[i] == '[' ) //如果是左括号等地字符,那么直接放入栈中
 9                 st.push(s[i]);
10             else {  //如果是右括号等地字符,那么取出栈顶字符,并与是s[i]匹配,如果匹配失败,直接返回false,否则继续比较
11                 char ch = st.top();
12                 st.pop();
13                 if( (s[i] == ')' && ch != '(') || (s[i] == '}' && ch != '{') || (s[i] == ']' && ch != '[') )    //匹配不成功的情况
14                     return false;
15             }
16         return st.top() == '#'; //如栈顶最后不为#,那么说明左空号等字符过多
17     }
18 };

 

posted on 2014-09-02 11:21  bug睡的略爽  阅读(140)  评论(0编辑  收藏  举报

导航