A 0ms C++ Solution using Stack


  • 0
    Y

    Since in the ASCII, the difference between '(' and ')' is 1, the difference between '[' and ']' is 2 and the difference between '{' and '}' is also 2.

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> stk;
            int i = 0;
            while(i < s.length()) {
                char ch = s[i];
                if((ch == '(')||(ch == '[')||(ch == '{')) {
                    stk.push(ch);
                    i++;
                } else if((stk.size() != 0)&&((stk.top() == ch - 1)||(stk.top() == ch - 2))) {
                    stk.pop();
                    i++;
                } else return false;
            }
            return stk.empty();
        }
    };

Log in to reply
 

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