leetcode-20. 有效的括号

 

 

class Solution {
public:
    bool isValid(string s) {

        int len = s.length();
        if(len==0)
            return true;

        vector<char> res;

        if(s[0]==')'||s[0]==']'||s[0]=='}') // 如果第一个元素就是是右括号,返回false
            return false;
        
        stack<char> st;
        for(int i = 0; i < len; i++){
            if(s[i]=='('||s[i]=='['||s[i]=='{'){  // 只要是左括号,直接入栈
               //cout<<"s[i]:"<<s[i]<<endl;
                st.push(s[i]);
            }
            else if(s[i]==')'){
               // cout<<"s[i]:"<<s[i]<<endl;
                //cout<<"s[i]:"<<st.top()<<endl;
                if(st.empty())  // 如果栈为空,又进入一个右括号,无法匹配,返回false;
                    return false;
                else if(st.top()=='(')  // 如果栈不空,进行匹配
                    st.pop();
                else if(st.top()!='(')
                    return false;
            }else if(s[i]==']'){
                if(st.empty())
                    return false;
                else if(st.top()=='[')
                    st.pop();
                else if(st.top()!='[')
                    return false;
            }else if(s[i]=='}'){
                if(st.empty())
                    return false;
                else if(st.top()=='{')
                    st.pop();
                else if(st.top()!='{')
                    return false;
            }
        }

        if(st.empty())  // 最后栈为空,返回true
            return true;
        else 
            return false;

    }
};

 

posted @ 2021-07-15 15:32  三一一一317  阅读(27)  评论(0)    收藏  举报