双指针:
c++
「朴素匹配」而言,一旦匹配失败,将会将原串指针调整至下一个「发起点」,匹配串的指针调整至起始位置,然后重新尝试匹配。「朴素匹配」的复杂度是
O(m*n)
class Solution {
public:
int strStr(string haystack, string needle) {
for(int i = 0; i + needle.size() <= haystack.size(); i++) {
int j = 0;
while(j < needle.size() && needle[j] == haystack[i + j]){
j++;
}
if(j == needle.size()){
return i;
}
}
return -1;
}
};
单指针 + 字符串切片:
python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
left=0
right = len(needle)
while right <= len(haystack):
if haystack[left:right] == needle:
return left
left += 1
right += 1
return -1
c++
c++ string 字符串切片 substr函数:string.substr(pos, n)
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()){
return 0;
}
int left=0;
int right = needle.size();
while((left+right) <= haystack.size()){
if (haystack.substr(left, right) == needle){
return left;
}
left++;
}
return -1;
}
};
KMP 算法
KMP 利用 “已匹配” 部分中相同的「前缀」和「后缀」来加速下一次的匹配。 KMP 的原串指针不会进行回溯(没有朴素匹配中回到下一个「发起点」的过程)