LeetCode28.实现StrStr
Question
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
Example
Example 1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0
Example 2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
Idea
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
Solution1:暴力解法
class Solution {
public:
int strStr(string haystack, string needle) {
int ln = needle.size(), lh = haystack.size();
for(int i = 0; i < lh; i++){
for(int j = 0; j < ln; j++){
if(haystack[i+j] != needle[j])break;
else if(j >= ln - 1) return i;
}
}
return -1;
}
};
Solution2:KMP算法
class Solution {
public:
int *buildNext(string p){
int m = p.size(), j = 0;
int *N = new int[m];
int t = N[0] = -1;
while(j < m-1){
if(t < 0 || p[t] == p[j]){
t++;j++;
N[j] = t; // 每次求N[j], 后面t = N[t]肯定是有值的
}else{
t = N[t]; // j > t
}
}
return N;
}
int strStr(string haystack, string needle) {
int *next = buildNext(needle);
int m = haystack.size(), i = 0;
int n = needle.size(), j = 0;
while(j < n && i < m){
if(0 > j || haystack[i] == needle[j]){
i++;j++;
}else{
j = next[j];
}
}
delete [] next;
if(j == n) return i-j;
return -1;
}
};