https://leetcode.com/problems/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.

思路:

考察stack的应用。

我的AC代码:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         int n=s.size();
 5         if(n%2==1)
 6             return false;
 7         stack<char> a;    //push,pop,top,size
 8          for(int i=0;i<n;i++){
 9             if(s[i]=='('|| s[i]=='['||s[i]=='{') 
10                 a.push(s[i]);
11             else if (a.empty()==false &&( (a.top()=='(' && s[i]==')') || (a.top()=='[' && s[i]==']') || (a.top()=='{' && s[i]=='}') ) )
12                 a.pop();
13             else 
14                 return false;
15          }
16          if(a.empty())
17             return true;
18          else return false;
19     }
20 };