Simple 2ms C++ solution.


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

  • 0
    Y

    Why you include the situation s[i]-myS.top()<-3?

    The ascii number of ')', ']', '}' is always larger than the '(' '[' '{'

    And another question is how can you know that if -3<s[i]-myS.top()<3 then the string will be valid?


Log in to reply
 

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