My solution without std::stack


  • 0
    F

    Inspired by andyreyes' solution.

    I used a vector as a "home-made" stack. It costs a little more memory since I initialized a std::vector with the length of string. It's just for a special situation: the input string is filled with all left brackets ("(((((((((((((...").

    class Solution {
    public:
        bool isValid(string s) {
            vector<char> st (s.length(), 0);
            int idx = 0;
            
            for (int i = 0; i != s.length(); ++i) {
                switch(s[i])
                    {
                        case '(':
                        case '{':
                        case '[':
                            st[idx++] = s[i];
                            break;
                        case ')':
                            if((idx == 0) || (st[--idx] != '(' ))
                                return false;
                            break;
                        case '}':
                            if((idx == 0) || (st[--idx] != '{' ))
                                return false;
                            break;
                        case ']':
                            if((idx == 0) || (st[--idx] != '[' ))
                                return false;
                            break;
    
                        default:
                            return false;
                    }
            }
            return (idx == 0);
        }
    };

Log in to reply
 

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