本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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         int n = s.size();
 5         if(n == 0)return true;
 6         stack<char> sta;
 7         sta.push('#');
 8         for(int i = 0; i < n; i++)
 9         {
10             switch(s[i])
11             {
12                 case '(': sta.push('('); break;
13                 case '{': sta.push('{'); break;
14                 case '[': sta.push('['); break;
15                 case ')': {
16                     char top = sta.top();
17                     if(top != '(')return false;
18                     else sta.pop();
19                     break;}
20                 case '}': {
21                     char top = sta.top();
22                     if(top != '{')return false;
23                     else sta.pop();
24                     break;}
25                 case ']': {
26                     char top = sta.top();
27                     if(top != '[')return false;
28                     else sta.pop();
29                     break;}
30             }
31         }
32         if(sta.size() == 1)return true;
33         else return false;
34     }
35 };

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3776395.html

 

posted @ 2014-06-08 16:39  tenos  阅读(594)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童