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         stack<char> S;
 5         for(int i = 0; i < s.length(); i++){
 6             if(!S.empty()){
 7                 char top = S.top();
 8                 if(pair(top,s[i])) S.pop();
 9                 else S.push(s[i]);
10             }else S.push(s[i]);
11         }
12         if(S.empty()) return true;
13         return false;
14     }
15     bool pair(char l, char r){
16         if(l == '(' && r == ')') return true;
17         if(l == '[' && r == ']') return true;
18         if(l == '{' && r ==  '}') return true;
19         return false;
20     }
21 };

 

posted on 2014-08-10 13:36  Ryan-Xing  阅读(81)  评论(0编辑  收藏  举报