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.

Solution:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         int len = s.length();
 5         if(len % 2 != 0) return false;
 6         else{
 7             stack<char> sta;
 8             sta.push(s[0]);
 9             for(int i = 1; i < len; i++){
10                 if(sta.empty()) sta.push(s[i]);
11                 else{
12                     if(s[i] == pair(sta.top())) sta.pop();
13                     else sta.push(s[i]);
14                 }
15             }
16             if(sta.empty()) return true;
17             else return false;
18         }
19     }
20     char pair(char ch){
21         switch(ch){
22             case '(': return ')';
23             case ')': return '(';
24             case '[': return ']';
25             case ']': return '[';
26             case '{': return '}';
27             case '}': return '{';
28         };
29     }
30 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4414997.html