7 Lines 0ms C++ solution with the ascii trick


  • -1
    H
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> left_ch;
            for(int i=0;i<s.length();i++){
                if(s[i]=='('||s[i]=='['||s[i]=='{') left_ch.push(s[i]);
                else if(left_ch.empty()||s[i]-left_ch.top()>2) return false; // )-(=1    ]-[=2   }-{=2
                else left_ch.pop();
            }
            return left_ch.empty();
        }
    };

  • 0
    M

    your code and trick is great~
    but is there any mistake in your comment?
    the '{' should be 123 and '}' is 125
    '[' is 91 and ']' is 93


  • 0
    H

    I am sorry, that is my mistake... I have fixed it


  • 0
    E

    Although it is said accepted... You can try "[)" and your output is true.
    s[i]-left_ch.top()>2||s[i]-left_ch.top()<1 should be correct.


Log in to reply
 

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