Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
這道題實現是爲了實現strStr()功能,但是更新後該函數返回值不再要求是char*,而是int,也即需要返回查找到的字符串的下標。
說白了,這道題其實就是爲了實現字符串匹配功能,爲了追求速度,使用修正後的KMP算法。
class Solution
{
public:
void get_next(int * next, char * T)
{
int i=0, j=-1;
next[0] = -1;
int len = strlen(T);
while(i<len-1)
{
if(j==-1 || T[i]==T[j])
{
++i;
++j;
if(T[i]!=T[j])
next[i] = j;
else
next[i] = next[j];
}
else
j = next[j];
}
}
int strStr(char *haystack, char *needle)
{
if(!haystack || !needle) return -1;
int len_needle = strlen(needle);
int len_haystack = strlen(haystack);
if(len_needle == 0 && len_haystack == 0) return 0;
if(len_needle > len_haystack) return -1;
int *next = new int[len_needle];
int i=-1, j=-1;
get_next(next, needle);
while(i<len_haystack && j<len_needle)
{
if(j==-1 || haystack[i]==needle[j])
{
++i;
++j;
}
else
j=next[j];
}
delete[] next;
if(j==len_needle)
return (i-len_needle);
else
return -1;
}
};
運行時間 12ms