Why my code got correct results on my Macbook but failed on LeetCode?


  • 0
    G
    class Solution {
    public:
        int longestValidParentheses(string s) {
            unsigned long len=s.length();
            int* f=new int[len];
            int* g=new int[len];
            int ans=0;
            for (int i=0;i<len;f[i]=0,g[i]=0,i++);
            for (int i=1;i<len;i++) {
                g[i]=f[i-1];
                if (s[i]==')' && s[i-f[i-1]-1]=='(') f[i]=f[i-1]+g[i-f[i-1]-1]+2;
                if (f[i]>ans) ans=f[i];
            }
            delete[] f;
            delete[] g;
            return ans;
        }
    };
    

    I failed on this input:
    ((()))((((((()))))((())(()())(()((()()(()()))((())((((()))(()())))))())))()())((()()))((((()()()()()((()())))(())((()(()((()))()()()))()(())()))))))()(()))((()()()()())(()()()))(())((())())

    I got correct answer which is 146 but got 148 on LeetCode.

    What's the matter?


  • 0
    G

    I've found where the bug is, which sometimes the value i-f[i-1]-1 maybe negative.


Log in to reply
 

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