Why did my code in c++ get runtime error?


  • 0
    L

    This is my first time to submit code in c++. Actually, it is c code. Can anybody tell me why my code got runtime error?

    char *strStr(char *haystack, char *needle) {
    if(NULL==haystack||NULL==needle)
    	return NULL;
    int plen = strlen(needle);
    int badChar[256];
    int np = 0;
    int i,j,k;
    
    for(i=0;i<256;i++)
    	badChar[i] = plen;
    
    while(np<plen)
    {
    	badChar[*(needle+np)] = plen-np-1;
    	np++;
    }
    
    int* goodSuffix = new int[plen];
    
    int prefix_index = plen;
    for(i=plen-1;i>=0;i--)
    {
    	goodSuffix[i] = prefix_index;
    	if(*(needle+i)==*(needle+plen-1-i)&&prefix_index==i+1)
    		prefix_index = i;
    }
    
    for(i=0;i<plen-1;i++)
    {
    	j = plen-1, k = 0;
    	while(k<i&&*(needle+j)==*(needle+i-k))
    	{j--;k++;}
    	if(*(needle+plen-1)==*(needle+i))
    		goodSuffix[j] = plen-1-i;
    }
    goodSuffix[plen-1] = 0;
    
    int slen = strlen(haystack);
    int sp = 0;
    while(sp<slen)
    {
    	i = plen-1;
    	while(i>=0&&*(haystack+sp+i)==*(needle+i))
    		i--;
    	if(i<0)
    		return haystack+sp;
    	sp += max(badChar[*(haystack+sp+i)],goodSuffix[i]);
    }
    
    return NULL;
    }

Log in to reply
 

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