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
2.KMP算法,32MS AC
嗯,关于为什么KMP算法会更慢的问题。。。之前做一个project,研究BF算法和KMP算法的性能,也发现KMP明显比BF慢很多。猜测是Next数组效果不很明显,然后经常访问数组带来更多的时间开销,嗯。
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数组效果不很明显,然后经常访问数组带来更多的时间开销,嗯。
相关文章推荐
- LeetCode 28. Implement strStr()(实现子串定位)
- [LeetCode]—Implement strStr() 寻找子串匹配第一个位置 (KMP)
- LeetCode-28. Implement strStr()
- LeetCode 28. Implement strStr()
- LeetCode28. Implement strStr()
- [LeetCode] 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- [LeetCode] 28. Implement strStr() 解题思路
- [Leetcode]28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr() (java实现)
- leetcode刷题记录-28. Implement strStr()
- Leetcode 28. Implement strStr()
- 28. Implement strStr()-leetcode-java
- leetCode 28. Implement strStr() 字符串
- 【LeetCode】28. Implement strStr() 解题报告
- [LeetCode]28. Implement strStr()
- leetcode 567. Permutation in String 寻找子串 + 滑动窗口