Solution in C++


  • 0
    S

    class Solution {
    public:
    bool isValid(string s) {
    int i = 0;
    stack<char> st;
    while(s[i]){

            if(s[i] == '('|| s[i] == '{' || s[i] == '['){
                st.push(s[i++]);
            }
            else {
                if(st.empty()){return false;}
                switch (s[i]){
                    case ')':
                        if('(' != st.top()){return false;}
                        break;
                    case '}':
                        if('{' != st.top()){return false;}
                        break;
                    case ']':
                        if('[' != st.top()){return false;}
                        break;
                    default:
                        return false;
                }
                i++;st.pop();
            }
        }
        return (st.empty()? true:false);
    }
    

    };


  • 0
    L

    The return statement :
    st.empty()? true:false
    is redundant because st.empty() will return true or false.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.