leetcode 28 : 实现strStr()
题目
算法思想 :这是典型的字符串匹配,所以本文采用经典的kmp算法,如果你不是很懂kmp算法的原理,https://www.cnblogs.com/yjiyjige/p/3263858.html,这个博主写的非常详细,大家可以直接参考,问题的关键是要匹配的子串的next数组如何求,换句话说是字串的前缀是否在后面出现。
int * getnext(string needle)
{
int *next = new int [needle.length()];
next[0] = -1;
int j = 0;
int k = -1;
while(j < needle.length()-1 )
{
if(k == -1 || needle[j] == needle[k])
{
j++;
k++;
next[j] = k;
}
else
k = next[k];
}
return next;
}
int strStr(string haystack, string needle) {
if(haystack == needle)
return 0;
else if(needle == "")
return 0;
if(needle.length() > haystack.length())
return -1;
int i = 0,j = 0;
int *next = getnext(needle);
while(i < (int)haystack.length() && j < (int)needle.length() )
{
if(j == -1 || haystack[i] == needle[j] )
{
i++;
j++;
}
else
j = next[j];
}
if(j == needle.length() )
return i-j;
else
return -1;
}