Why my answer in C++ can't pass the case"(()()"


  • 0
    C

    class Solution
    {

    public:

    Solution(int a = 0){};
    
    int longestValidParentheses(string s) {
    
        stack<char> stack;
        int count = 0;
        for(int i = 0; i < s.size(); i++){
    
            if(s[i] == '(')
                stack.push(s[i]);
            else{
                if (!stack.empty() && stack.top() == '('){
                    count += 2;
                    stack.pop();
                }
                else{
                    if (count > a)
    
                        a = count;
                    count = 0;
                }
            }
        }
       if (count > a)
    
            a = count;    
        return a;
    }
    

    private:
    int a;
    };


  • 1
    J

    First, it's not recommended to use shared variables because the OJ may use the same Solution instance multiple times. You should reset it every the first time you use them.

    Second, your algorithm is wrong even if you solve the first problem. Please consider such test case: ()(()


Log in to reply
 

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