leetcode 28. Implement strStr()
2017-07-22 10:32
1361 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解:KMP算法挺难理解的,看了几遍记住之后,做到这题只记得大体的思路但是算法细节有不理解了,先来个brute-force算法压压惊,再去看看KMP。
brute-force算法
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.length();
int len2 = needle.length();
if(!len2) return 0;
for(int i = 0; i < len1 - len2 + 1; ++i){
for(int j = 0; j < len2; ++j){
if(haystack[i + j] != needle[j]) break;
if(j == len2 - 1) return i;
}
}
return -1;
}
};TODO:KMP
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解:KMP算法挺难理解的,看了几遍记住之后,做到这题只记得大体的思路但是算法细节有不理解了,先来个brute-force算法压压惊,再去看看KMP。
brute-force算法
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.length();
int len2 = needle.length();
if(!len2) return 0;
for(int i = 0; i < len1 - len2 + 1; ++i){
for(int j = 0; j < len2; ++j){
if(haystack[i + j] != needle[j]) break;
if(j == len2 - 1) return i;
}
}
return -1;
}
};TODO:KMP
相关文章推荐
- 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()
- 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() KMP算法解题
- LeetCode - 28. Implement strStr()
- [Leetcode] 28. Implement strStr()
- LeetCode28. Implement strStr()
- Leetcode28. Implement strStr()
- Leetcode—— 28. Implement strStr()