您的位置:首页 > 其它

LeetCode | 28. Implement strStr()——寻找子串

2017-05-24 15:44 411 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

1。暴力算法,6MS AC

class Solution {
public:
int strStr(string haystack, string needle)
{
int len1 = haystack.length(), len2 = needle.length();
int flag = 0;

for(int i=0;i<=len1-len2;i++)
{
flag = 1;
for(int j=0;j<len2;j++)
{
if(haystack[i+j] != needle[j])
{
flag = 0; break;
}
}
if(flag)
{
return i;
}
}

return -1;
}

};


2.KMP算法,32MS AC

class Solution {
public:
int _next[1000000];
int strStr(string haystack, string needle)
{
int len1 = haystack.length(), len2 = needle.length();
int i = 0, k = -1, j = 0;
_next[0] = -1;
while ( i < len2-1 ) /* 计算next[i+1] */
{
while (k >= 0 && needle[i] != needle[k])
k = _next[k]; /* p0…pi中最大的相同的前后缀长度k */
i++; k++;
_next[ i ] = k;
}
i = 0; j = 0;
while ( i < len2 && j < len1 ) //反复比较
{
if (i == -1 || needle[i] == haystack[j])
{
i++; j++;
} //继续匹配下一个字符
else
i = _next[i]; //j不变, i后退
}
//匹配成功,返回p中第一个字符在t中的位置
if ( i >= len2)
return ( j- len2);
else
return -1; //匹配失败
}

};


嗯,关于为什么KMP算法会更慢的问题。。。之前做一个project,研究BF算法和KMP算法的性能,也发现KMP明显比BF慢很多。猜测是Next数组效果不很明显,然后经常访问数组带来更多的时间开销,嗯。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string leetcode