28. 找出字符串中第一个匹配项的下标
题目介绍
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = “sadbutsad”, needle = “sad”
输出:0
解释:“sad” 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = “leetcode”, needle = “leeto”
输出:-1
解释:“leeto” 没有在 “leetcode” 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解
双指针法
先简要规定,我们要做的是在h字符串中找到与n字符串匹配的子字符串。
使用两个指针
i
,
j
i,j
i,j,其中
i
i
i指向h数组中需要被判断的字符串的第一个元素,
j
j
j指向n数组中被判断的元素。
如果元素相等,则j向前推进;
如果元素不同,则i向前推进,j=0。
class Solution {
public:
int strStr(string haystack, string needle) {
int i=0,j=0;
while(i<haystack.size() && j<needle.size()){
if(haystack[i+j] == needle[j])
{
j++;
}
else{
j=0;
i++;
}
}
if(j==needle.size())
{
return i;
}
return -1;
}
};
大名鼎鼎的KMP算法!
思路过于复杂,具体可百度。
简言之,KMP算法永不退回 h 字符串的指针 i ,而是借助 dp 数组中储存的信息把 n 字符串 移到正确的位置继续匹配,时间复杂度只需 O(N),用空间换时间,所以我认为它是一种动态规划算法。
所以我们需要一个辅助数组 next 用来存储 n 字符串中字符不匹配时该移动的位置,因此此数组只与 n 字符串有关。其数组也可看做一个确定有限状态机。
讲解的很有道理,但是他贴的代码有问题
https://www.zhihu.com/question/21923021/answer/281346746
class Solution {
public:
void getNext(int* next, const string& s) {
int j = -1;
next[0] = j;
for(int i = 1; i < s.size(); i++) { // 注意i从1开始
while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了
j = next[j]; // 向前回溯
}
if (s[i] == s[j + 1]) { // 找到相同的前后缀
j++;
}
next[i] = j; // 将j(前缀的长度)赋给next[i]
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = -1; // // 因为next数组里记录的起始位置为-1
for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始
while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配
j = next[j]; // j 寻找之前匹配的位置
}
if (haystack[i] == needle[j + 1]) { // 匹配,j和i同时向后移动
j++; // i的增加在for循环里
}
if (j == (needle.size() - 1) ) { // 文本串s里出现了模式串t
return (i - needle.size() + 1);
}
}
return -1;
}
};