Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Solution:
char *strStr(char *haystack, char *needle) {
int lenA = strlen(haystack);
int lenB = strlen(needle);
if(lenA>=0&&lenB==0)
return haystack;
if(lenA==0)
return NULL;
vector<int> next(lenB, 0);
next[0] = -1;
int cur = 0;
int k =-1;
while(cur<lenB-1)
{
if(k==-1||needle[cur]==needle[k])
{
cur++;
k++;
next[cur] = k;
}
else
k = next[k];
}
k = -1;
int curA = 0;
int curB = 0;
while(curA<lenA)
{
if(curB==-1||haystack[curA]==needle[curB])
{
curA++;
curB++;
}
else
curB = next[curB];
if(curB == lenB)
return &haystack[curA-curB];
}
return NULL;
}
No comments:
Post a Comment