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

Valid Parentheses

时间:2015-01-19 22:31:41      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

第一次提交时runtime error ,错误串是“]”,而在code blocks (g++)下编译运行结果都是对的。后来发现时code blocks 下当栈为空时,stack.top()访问时没报错。而OJ认为是指针错误,修改再提交就OK了。

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         if(s.empty())
 5             return true;
 6 
 7         stack<char> sta;
 8         int length;
 9         length = s.size();
10 
11         for(int i=0;i<length;i++)
12         {
13             if(s[i]==[ || s[i]==( || s[i]=={)
14                 sta.push(s[i]);
15             else{
16               switch(s[i])
17               {
18                   case ]:
19                       if(sta.empty() || sta.top()!=[)
20                         return false;
21                         sta.pop();
22                        break;
23                   case ):
24                       if(sta.empty() || sta.top()!=()
25                             return false;
26                             sta.pop();
27                        break;
28                   case }:
29                       if(sta.empty() || sta.top()!={)
30                         return false;
31                         sta.pop();
32                       break;
33                   default:
34                       break;
35               }
36             }
37 
38         }
39         if(!sta.empty())
40             return false;
41         else
42             return true;
43     }
44 };

 

Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/ZhangYushuang/p/4234800.html

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