码迷,mamicode.com
首页 > 其他好文 > 详细

valid parentheses

时间:2015-08-16 01:59:17      阅读:97      评论: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.
 
思路分析:
首先遍历字符串,
如果是左括号(3种)则入栈,
否则(说明是右括号),首先判定栈是否已空,
          若空(说明当前的右括号不会有左括号与之匹配),返回false,
          否则,出栈,并且将这一元素与当前正在遍历的元素进行匹配,若是不匹配则返回false(无效的括号字符集),否则遍历继续进行。
遍历完括号字符串之后,若是,栈为空,返回true
否则返回false,程序结束!
 
代码如下:
 1 #include<iostream>
 2 #include<stack>
 3 #include<vector>
 4 using namespace std;
 5 
 6 class Solution {
 7 private:
 8     stack<char> sta;
 9 public:
10     bool isValid(string s) {
11         int len = s.length();
12         for (int i = 0; i < len; ++i)
13         {
14             if (s[i] == ( || s[i] == [ || s[i] == {)
15                 sta.push(s[i]);
16             else
17             {
18                 if (sta.empty())//这个地方不先判空,则遇到()] 这种情况,程序就直接崩溃了,因为对一个空栈top,你懂的
19                     return false;
20                 char temp = sta.top();
21                 sta.pop();
22                 if (temp==(&&s[i]==)||temp==[&&s[i]==]||temp=={&&s[i]==})
23                 {
24                     ;
25                 }
26                 else return false;
27 
28             }
29         }
30         if (sta.empty())
31             return true;
32         else return false;
33     }
34 };
35 
36 int main()
37 {
38     Solution test;
39     string val = "()()]";
40     bool result = test.isValid(val);
41     cout << result << endl;
42     return 0;
43 }

 

valid parentheses

标签:

原文地址:http://www.cnblogs.com/chess/p/4733505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!