Implement strStr()
问题描述:找到字符串中某个字串,并返回该字串第一次出现时首个字符的位置。
问题解决:这道题是数据结构上一道非常经典的题目,然而为了偷懒我还是没用KMP算法。
class Solution {
public:
int strStr(string haystack, string needle) {
int nlen=needle.length(),hlen=haystack.length();
if(nlen==0) return 0;
if(hlen==0) return -1;
char fir=needle[0];
for(int i=0;i<hlen;i++)
{
if(haystack[i]==fir)
{
int j,k;
for(j=i+1,k=1;k<nlen;j++,k++)
{
if(haystack[j]!=needle[k])
break;
}
if(k==nlen)
return i;
}
}
return -1;
}
};
only beats 15.89 % of cpp submissions.