LeetCode 28 找出字符串中第一个匹配项的下标
1. 题目地址
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/?envType=study-plan-v2&envId=top-interview-150
2. 题解
这题直接用kmp算法求解即可。关于kmp算法可以参考之前的博客,这里不再赘述。
唯一需要注意的是:之前讲述的kmp算法字符串下标从1开始,这里是从0开始。下标不同可能会导致i,j以及next数组的值不同,这里需要注意,但是思想都是一致的。
3. 代码
class Solution {
public:
int strStr(string haystack, string needle) {
int ne[10010];
ne[0] = -1;
int result = -1;
for(int i = 1, j = -1; i < needle.size(); i ++){
while(j != -1 && needle[i] != needle[j + 1]){
j = ne[j];
}
if(needle[i] == needle[j + 1]){
j++;
}
ne[i] = j;
}
for(int i = 0, j = -1; i < haystack.size(); i ++){
while(j != -1 && haystack[i] != needle[j + 1]){
j = ne[j];
}
if(haystack[i] == needle[j + 1]){
j++;
}
if(j == needle.size() - 1){
result = i - j;
break;
}
}
return result;
}
};