LeetCode 20. Valid Parentheses(c++)

利用栈的操作,遇到"(","[","{"即进栈,遇到")","]","}"判断是否与栈顶匹配,若不匹配则false。

class Solution {
public:
    bool isValid(string s) {
        stack<char> c;
        for(int i=0;i<s.size();i++){
            if(!c.empty()){
            if(s[i]=='('||s[i]=='{'||s[i]=='[')
                c.push(s[i]);
            else if(s[i]==')'){
                if(c.top()=='(') c.pop();
                else return false;
            }
            else if(s[i]=='}'){
                if(c.top()=='{') c.pop();
                else return false;
            }
            else if(s[i]==']'){
                if(c.top()=='[') c.pop();
                else return false;
            }
            }
            else c.push(s[i]);
        }
        if(!c.empty()) return false;
        return true;
    }
};

 

posted @ 2019-04-28 19:59  星辰大海。  阅读(170)  评论(0编辑  收藏  举报