Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns achar *
or String
, please click the reload button to reset your code definition.
典型的KMP算法,但无奈下午时候并不会用,所以本来想法是使用简单字符串匹配算法,M*N的时间复杂度,但是无奈对aaaaaaa...ab 和aaa..b的问题,还是超时了。先说简单算法:
//事后Time Limit Exceeded,发现我想多了,M*N的时间复杂度也是不行
//只能KMP啦!
if(haystack==""&& needle=="") return 0;//空串考虑
if(haystack=="") return -1;//空串中查找非空串,肯定报错
if(needle=="") return 0;//子串为空
int i=0;
int j=0;
int hlen=haystack.length();
int nlen=needle.length();
if(nlen>hlen) return -1;
int k=i;
while(i!=hlen && j!=nlen)
{
if(haystack[i+j]==needle[j]) ++j;
else{
j=0;
++i;
}
}
if(j==nlen) return i;
else return -1;
下面决定攻克KMP算法,每次都似懂非懂,这下多谢博客:http://www.cppblog.com/oosky/archive/2006/07/06/9486.html 终于算是弄懂了。
void get_next(string needle,vector<int> &next)//next
{
int nlen=needle.size();
int k=-1,j=0;
next.push_back(-1);
while(j!=nlen)
{
if(k==-1 || needle[k]==needle[j])//-1很巧妙
{
j++;
k++;
if(needle[k]!=needle[j])
next.push_back(k);
else next.push_back(next[k]);
}
else
k=next[k];
}
}
int strStr(string haystack, string needle) {
//只能KMP啦!
if(haystack.empty() && needle.empty()) return 0;
if(haystack.empty()) return -1;
if(needle.empty()) return 0;
vector<int> next;
get_next(needle,next);
int hlen=haystack.size(),nlen=needle.size();
if(hlen<nlen) return -1;
int i=0,j=0,index=0;
while(i<hlen && j<nlen)
{
if(haystack[i]==needle[j])//相等
{
++i;
++j;
}
else
{
index=index+j-next[j];
if(next[j]!=-1) //判断next[j]是否为-1
j=next[j]; //不是-1,那么j回退到next[j]的位置
else //否则,j回退到0,i右移
{
i++;
j=0;
}
}
}
if(j==nlen) return index;
else return -1;
}