My 0ms C++ solution using stack and ASCII


  • 0
    A
    class Solution {
    

    public:
    bool isValid(string s) {
    stack<char> brackets;
    for(int i=0;i<s.length();i++)
    {
    if(s[i]!='(' && s[i]!=')' && s[i]!='[' && s[i]!=']' && s[i]!='{' && s[i]!='}')
    return false;
    else
    {
    if(s[i]=='(' || s[i]=='[' || s[i]=='{')
    brackets.push(s[i]);

                    else
                    {
                        if(brackets.empty() || (s[i] - brackets.top()!=1  &&  s[i] - brackets.top()!=2))    return false;
                        else    brackets.pop();
                    }
                }
        }
        return brackets.size()==0;
    }
    

    };


Log in to reply
 

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