题目
解法:
brutal in python:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
n = len(needle)
for i in range(len(haystack)-n+1):
if haystack[i:i+n] == needle:
return i
return -1
时间复杂度:O((N-L)*L), L为needle长度,N为haystack长度
C++
采用双指针法,当碰到相同的needle首字母时再开始比较。时间复杂度与第一种解法相同。要尤其注意边界条件。
class Solution {
public:
int strStr(string haystack, string needle) {
int L = needle.length(),n = haystack.length();
if (L==0) return 0;
int pn = 0;
while (pn<n-L+1){
while (pn<n-L+1 && haystack[pn] != needle[0]) pn++;
int curr_len = 0, pL = 0;
while (pn<n && pL<L && haystack[pn]==needle[pL]){
pn++;
pL++;
curr_len++;
}
if (curr_len==L) return pn-L;
pn = pn-curr_len+1;
}
return -1;
}
};