Valid Parentheses

问题:The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.,判断符合条件的符号([])也符合
分析:遇到左边符号进栈,右边符号就将栈顶出栈,若和当前遍历的符号相对应则继续遍历下一个符号,若不对应返回false

class Solution {
public:
    bool isValid(string s) {
        stack<char> S;
        char st;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(' || s[i]=='[' || s[i]=='{') S.push(s[i]);
            else if(S.empty()) return false;//如果栈为空出栈会导致RE
            else if(s[i]==')') 
            {
                st=S.top();
                if(st=='(') S.pop();
                else return false;
            }
            else if(s[i]==']')
            {
                st=S.top();
                if(st=='[') S.pop();
                else return false;
            }
            else if(s[i]=='}') 
            {
                st=S.top();
                if(st=='{') S.pop();
                else return false;
            }
        }
        if(!S.empty()) return false;
        return true;
    }
};

  

原文地址:https://www.cnblogs.com/zsboy/p/3895289.html