LeetCode: Valid Parentheses

来源:互联网 发布:windows net snmp 编辑:程序博客网 时间:2024/05/19 09:17
class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<char> st;
        for(int i=0;i<s.length();i++){
            if(s[i]=='(')
                st.push(s[i]);
            else if(s[i]==')'){
                if(st.empty()||st.top()!='(')
                    return false;
                st.pop();
            }
            else if(s[i]=='{')
                st.push(s[i]);
            else if(s[i]=='}'){
                if(st.empty()||st.top()!='{')
                    return false;
                st.pop();
            }
            else if(s[i]=='[')
                st.push(s[i]);
            else if(s[i]==']'){
                if(st.empty()||st.top()!='[')
                    return false;
                st.pop();
            }
            else
                return false;
        }
        return st.empty();
    }
};
原创粉丝点击