代码改变世界

leetcode - Valid Parentheses

2013-11-05 23:17  张汉生  阅读(144)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         stack<char> sc;
 7         int len = s.length();
 8         for (int i=0; i<len; i++){
 9             char c = s.at(i);
10             switch(c){
11                 case '(':
12                 case '{':
13                 case '[':
14                     sc.push(c);
15                     break;
16                 case '}':
17                     if (sc.empty() ||sc.top()!='{')
18                         return false;
19                     else sc.pop();
20                     break;
21                 case ']':
22                     if (sc.empty() ||sc.top()!='[')
23                         return false;
24                     else sc.pop();
25                     break;
26                 case ')':
27                     if (sc.empty() ||sc.top()!='(')
28                         return false;
29                     else sc.pop();
30                     break;
31                 default:
32                     return false;
33             }
34         }
35         if (!sc.empty())
36             return false;
37         return true;
38     }
39 };