题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
KMP实现
next数组的实现:
求X位置的最大前缀匹配,连续不匹配的情况:
求x位置的最大前缀匹配,往前能找到的情况
class Solution {
public:
vector<int> getNext(string s){
int n = s.size(),cnt = 0;
vector<int> next(n,0);
next[0] = -1;
// 注意这里不自动+1
for(int i = 2;i < n;){
// 相同时
if(s[cnt] == s[i-1]) next[i++] = ++cnt;
else{
// 不同时,往前找cnt位置的最大匹配
if(cnt > 0) cnt = next[cnt];
else next[i++] = 0;
}
}
return next;
}
// kmp实现
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
vector<int> next = getNext(needle);
int i = 0,j = 0;
while(i < needle.size() && j < haystack.size()){
if(haystack[j] == needle[i]){
i++;j++;
}else{
if(next[i] == -1) j++;
else i = next[i];
}
}
if(i == needle.size()){
return j-i;
}
return -1;
}
};