c++ solution using stack


  • 0
    H
    class Solution {
    public:
        bool isValid(string s) {
            vector<char> char_stack;
            
            for (int i = 0; i != s.length(); i++) {
                if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                    char_stack.push_back(s[i]);
                } else {
                    if (s[i] == '}' || s[i] == ']') {
                        if (char_stack.size() == 0 || char_stack.back() != s[i]-2) return false;
                    } else {
                        if (char_stack.size() == 0 || char_stack.back() != s[i]-1) return false;
                    }
                    char_stack.pop_back();
                }
            }
            
            return char_stack.size() > 0 ? false : true;
        }
    };
    

Log in to reply
 

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