There is a bug in my code, but it is accepted!


  • 0
    M

    My code passes OJ, but for the below test case, it actually gave the wrong answer. It is invalid, but my code thought it was valid.

    [](])

    class Solution {
    public:
        bool isValid(string s) {
            if (s == "") {
                return true;
            }
            stack<char> parenContainer;
            map<char, char> pairs;
            pairs['}'] = '{';
            pairs[']'] = '[';
            pairs[')'] = '(';
            for (string::iterator it = s.begin(); it != s.end(); ++it) {
                const char tmp = *it;
                if (tmp == '{' || tmp == '[' || tmp == '(') {
                    parenContainer.push(tmp);
                }
                else if (tmp == '}' || tmp == ']' || tmp == ')') {
                    if (parenContainer.empty()) {
                        return false;
                    }
                    if (parenContainer.top() == pairs[tmp]) {
                        parenContainer.pop();
                    }  // BUG: should push into stack if not.
    
                }
            }
            return parenContainer.empty();
        }
    };

  • 0

    Thanks for the test case! Test case was added.


Log in to reply
 

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