My easy understanding CPP code with one stack in 0ms


  • 0
    K
    bool isValid(string s) {
        bool res=true;
        int n=s.size();
        stack<char> v;
        for(int i=0;i<n;i++){
            if(s[i]=='('||s[i]=='['||s[i]=='{')
            v.push(s[i]);
            else{
                if(!v.empty()&&(s[i]==')'&&v.top()=='('||s[i]==']'&&v.top()=='['||s[i]=='}'&&v.top()=='{')){
                    v.pop();
                    }
                else{
                    res=false;
                    break;
                    }
                }
            }
            if(!v.empty())
            {
                res=false;
            }
            return res;
        }

Log in to reply
 

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