题目:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Solution:
使用了KMP算法,具体介绍在网上有诸多文章介绍,我的博客算法里有篇我的学习指南:
int strStr(string haystack,string needle)
{
if(needle == "")
return 0;
if(haystack == "")
return -1;
return Search(needle,haystack);
}
int Search(string pattern,string original)
{
int *next = BuildNext(pattern);
for(int i=0;i<pattern.size();i++)
cout<<next[i]<<" ";
cout<<endl;
int n = original.size();
int j = 0;
int pos = -1;
for(int i = 0;i<n;i++)
{
while(j > 0 && original[i] != pattern[j])
{
j = next[j];
if(j == -1) //因为我的数组是从0开始的,所以设置初始为-1,其实还是从第一位开始比较,设置下,以防后面越界。
j = 0;
}
if(original[i] == pattern[j])
j++;
if(j == pattern.size())
{
pos = i - j+1;
j = next[j-1];//数组最后一位是next[j-1]。
if(j==-1)
j=0;
break;//第一个匹配的成功就跳出
}
}
return pos;
}
int* BuildNext(string pattern)
{
int n = pattern.size();
int* next = new int[n]; //next数组存放跳转链表
int j = 0;
int k = -1;
next[0] = -1;//首位为-1
while(j < n-1)
{
if(k == -1 || pattern[j] == pattern[k])
{
if(pattern[j+1] == pattern[k+1])
{
next[++j] = next[++k];
}
else
next[++j] = ++k;
}
else
{
k = next[k];
}
}
return next;
}