首页 > 其他 > 详细

Valid Parentheses

时间:2014-09-02 12:16:04      阅读:159      评论:0      收藏:0      [点我收藏+]

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 };

 

Valid Parentheses

原文:http://www.cnblogs.com/bugfly/p/3951061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!