28找出字符串中第一个匹配的下标
简单的模式匹配:主串指针回溯,时间复杂度O(mn)
KMP算法:主串指针不回溯,时间复杂度O(m+n)
- KMP的代码:双指针,主串指针和模式串指针,主串指针不回溯,模式串指针指向下一个字符或者指向next数组的值;
- next数组:双指针,一个指向next数组的下标从0开始递增,一个指向插入这个位置的值。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size() == 0) return 0;
int nextLength = needle.size();
vector<int> next(nextLength);
//处理next数组,需要考虑next数组长度等于0,1,大于1
if(needle.size() == 1) next[0] = -1;
else{
next[0]= -1, next[1] = 0;
int pos = 0;
for(int npos = 2; npos < nextLength; npos++){//i指向字符串next的每一位,pos给next[i]赋值
pos = next[npos - 1];
while(pos != 0 && needle[npos-1]!=needle[pos]) pos = next[pos];
//cout << npos << endl;
if(needle[npos-1] == needle[pos]){ next[npos]=pos+1; }
else next[npos]=0;
}
}
int i = 0,j = 0;
//i指向主串,j指向模式串
while(i < haystack.size()){
if((j == -1) || (haystack[i] == needle[j])) {
i++, j++;
if(j == needle.size()) return (i-j);
}
else{
j = next[j];
}
}
return -1;
}
};
459重复的字符串
采用确定一个子字符串,再主串中判断是否是主串的字符串,不是继续找下一个,直到找到主串的一半,如果还是不是,则返回false。
时间复杂度O(n^2)
空间复杂度O(1)
class Solution {
public:
bool repeatedSubstringPattern(string s) {
bool str = true;
int length = s.size();
if(length <= 1) return false;
for(int i = 0; i * 2 < length; i++){
if(length % (i+1) == 0){
str = true;
for(int j = i+1; j < s.size(); j++){
if(s[j] != s[j-i -1]){
str = false;break;
}
}
if(str) return true;
}
}
return false;
}
};