Monday, September 11, 2017

20. Valid Parentheses

https://leetcode.com/problems/valid-parentheses/description/

    bool isValid(string s) {
        if(s.size() == 0) return true;
        stack<char> st;
        for(char c : s){
            switch(c) {
                case '{': st.push(c); break;
                case '(': st.push(c); break;
                case '[': st.push(c); break;
                case '}':
                    if(st.empty()||st.top()!='{') return false;
                    else st.pop();
                    break;
                case ')':
                    if(st.empty()||st.top()!='(') return false;
                    else st.pop();
                    break;
                case ']':
                    if(st.empty()||st.top()!='[') return false;
                    else st.pop();
                    break;
            }
        }
        if(st.empty()) return true;
        else return false;
    }

No comments:

Post a Comment