您的位置:首页 > 编程语言 > C语言/C++

LeetCode:Implement strStr()

2016-07-13 18:50 344 查看
一、问题描述

Implement strStr().

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

方法一暴力求解,方法二KMP算法

三、代码

方法一:

class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack==""&&needle ==""|| needle =="") return 0;
int i,j;
for(i = 0,j = 0; i < haystack.size()&& j < needle.size();){
if(haystack[i] == needle[j]){
++i;
++j;
}else{
i = i - (j - 1);
j = 0;
}
}

return j != needle.size() ? -1 : i - j;
}
};


方法二:

class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int i, j;
// preprocess
vector<int> b(needle.length() + 1, -1);
i = 0;
j = -1;
b[0] = j;
while(i < needle.length()){
while(j != -1 && needle[i] != needle[j]) j = b[j];
++i, ++j;
b[i] = j;
}

// find
i = 0;
j = 0;
while(i < haystack.length()){
while(j != -1 && haystack[i] != needle[j]) j = b[j];
++i, ++j;
if(j == needle.length()) return i - j;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode kmp C++