C++ stack solution


  • 0
    J
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> stk;
            for(int i = 0;i<s.size();i++)
            {
                if(s[i]=='(' || s[i]=='[' || s[i]=='{') stk.push(s[i]);
                else
                {
                    if(stk.empty()) return false;
                    else
                    {
                        if(s[i]==')')  
                        {
                            if(stk.top()!='(') return false;
                            else stk.pop();
                        }
                        else if(s[i]==']')  
                        {
                            if(stk.top()!='[') return false;
                            else stk.pop();
                        }
                        else if(s[i]=='}')  
                        {
                            if(stk.top()!='{') return false;
                            else stk.pop();
                        }
                    }
                }
            }
            return stk.empty()?true:false;
        }
    };
    

Log in to reply
 

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