2ms C++ code using stack


  • 1
    R
    bool isValid(string s) {
        stack<char> brackets;
        string::iterator it;
        for(it = s.begin();it<s.end();++it){
            if ((*it =='{') || (*it == '[') || (*it == '(')) {brackets.push(*it);}
            if ((*it == '}') || (*it == ')') || (*it == ']')) {
                if(brackets.empty() || abs((int)brackets.top() -(int) *it > 2)) {return false;}
                else {brackets.pop();}
            }
        }
        return brackets.empty()?true:false;
    }
    

    I think deque will be faster than stack. Anyway, the code with deque is similar with this one.


  • 0
    R

    Your code is broken, will return true for
    s = "(]"

    It fails because c++ char is unsigned.


  • 0
    R

    thanks. I have fixed the issue.


Log in to reply
 

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