Why my code always runtime error on oj but passed local?


  • 0
    G

    OJ side hello, ll case will report runtime error. but passed local.

    void buildNext(char* needle, int* next)
    {
    int len = strlen(needle);
    next[0] = 0;
    for (int i = 1; i<len; i++)
    {
    if (needle[next[i - 1]] == needle[i])
    {
    next[i] = next[i - 1] + 1;
    }
    else
    {
    if (needle[i] == needle[0]) next[i] = 1;
    else
    next[i] = 0;
    }

        }
    
    }
    
    char *strStr(char *haystack, char *needle) {
        if (haystack == NULL || needle == NULL || strlen(needle)>strlen(haystack)) return NULL;
        int len1 = strlen(haystack);
        int len2 = strlen(needle);
        int* next = (int*)malloc(len2);
        memset(next, 0, len2*sizeof(int));
        buildNext(needle, next);
        int i = 0;
        int index = 0;
        char* result = NULL;
        for (int i = 0; i<len1; ++i)
        {
            while (index >0 && needle[index] != haystack[i])
            {
                //not match need back
                index = next[index - 1];
            }
    
            if (needle[index] == haystack[i])
            {
                index++;
            }
    
            if (index == len2)
            {
                result = haystack + i - len2 + 1;
                break;
            }
        }
    
        return result;
    }

Log in to reply
 

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