Implement strStr()
Solution 1
从数据复杂度上来看肯定是可以直接暴力过的,但是前面做了好几道双指针维护的问题,所以这一个题也可以通过双指针分别维护主串和子串进行检查。检查逻辑如下:
- 如果当前子串指针在末尾,匹配完成,返回主串索引前的位置(前一个位置,实现过程中多加了一位)
- 如果两个指针对应地字符相同,同时加一位
- 如果不相同,子串指针重置,主串指针回退对应个数减一个位置(相当于重置后前进了一位)
- 整个过程以主串指针到达末尾中止
对于边界条件的处理其实有点麻烦……不过C++的String的末尾有一个\0
,可以用此进行处理(不过我没用,懒得弄了)。
- 时间复杂度:最坏 O ( ( N − L ) L ) O((N-L)L) O((N−L)L),其中 N N N为主串的长度, L L L为子串的长度,实际效率要远低于此
- 空间复杂度: O ( 1 ) O(1) O(1),只维护常数个状态量
class Solution {
public:
int strStr(string haystack, string needle) {
int ans = -1;
if (needle.size() == 0) {
ans = 0;
return ans;
}
else if (haystack.size() == 0) {
ans = -1;
return ans;
}
int posH = 0, posN = 0;
while (posH < haystack.size()) {
if (haystack[posH] == needle[posN]) {
posH++;
posN++;
}
else {
posH -= posN;
posN = 0;
posH++;
}
if (posN == needle.size()) {
ans = posH - posN;
break;
}
}
return ans;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
ans = -1
if len(needle) == 0:
return 0
if len(haystack) == 0:
return -1
posH, posN = 0, 0
while posH < len(haystack):
if haystack[posH] == needle[posN]:
posH += 1
posN += 1
else:
posH -= posN
posN = 0
posH += 1
if posN == len(needle):
ans = posH - posN
break
return ans