28.strStr() 双指针 && KMP算法
1、双指针法
一开始两个指针 i, j指向两个字符串的起始位置
如果不匹配,则将主串的指针移动一位,直到出现匹配为止;
若当前位置相等,两个指针一起向后移动一位。
若当前为止不相等,则主串的指针回到出现匹配的后一位;子串的指针回到 初始值。
若j移动到子串的最后一位时,匹配成功。
int strStr(string haystack, string needle)
{
int lh = haystack.size();
int ln =needle.size();
int i = 0, j = 0;
if(needle.empty())return 0;
while(i < lh)
{
if(haystack[i] == needle[j])
{
i++;
j++;
if(j == ln)
return i-j;
}
else
{
i = i - j + 1;
j = 0;
}
}
return -1;
}
时间复杂度尾 O(m*n),空间复杂度O(1)。
2、KMP算法
前缀:包含首字母,不包含尾字母的所有子串。
后缀:包含尾字母,不包含首字母的所有子串。
重点求最长相等前后缀。
void getNext(int next[],string s)//求next数组
{
int i, j = 0;
next[0] = 0;
for(i = 1; i < s.size(); i++)
{
while(j > 0 && s[i] != s[j])//j>0,因为有 j-1
j = next[j - 1];//从 j-1对应的值开始回退
if(s[i] == s[j])
j++;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if(needle.empty())
return 0;
int i, j = 0;
int lh = haystack.size();
int ln = needle.size();
int next[ln];
getNext(next,needle);
for(i = 0; i < lh; i++)
{
while(j > 0 && haystack[i] != needle[j])
j = next[j - 1];
if(haystack[i] == needle[j])
j++;
if(j==ln)
return (i-ln+1);
}
return -1;
}
时间复杂度尾 O(m+n),空间复杂度O(n)。
参考链接:
https://mp.weixin.qq.com/s?__biz=MzUxNjY5NTYxNA==&mid=2247484451&idx=1&sn=46f85138f1560842ea33e327b652cf2a&scene=21#wechat_redirect描述