KMP
vector<int> GetNext(string &input){
vector<int> nx(input.size() + 1,-1);
int i = 0,j = -1,len = input.size();
while(i < len){
if(j == -1 || input[i] == input[j]){
nx[++i] = ++j;
}else j = nx[j];
}
return nx;
}
int GetIndex(string &a,string &b){
vector<int> nx = GetNext(b);
int i = 0,j = 0,alen = a.size(),blen = b.size();
while(i < alen && j < blen){
if(j == -1 || a[i] == b[j]) i++,j++;
else j = nx[j];
}
if(j == blen) return i - j;
return -1;
}
Rabin-Karp 算法
const int hashCode = 137;
void Gethash(string &input,vector<long long int> &h,vector<long long int> &p){
h.assign(input.size() + 2,0);
p.assign(input.size() + 2,1);
for(int i = 0;i < input.size(); i++){
h[i + 1] = int(h[i] * hashCode + input[i]);
p[i + 1] = int(p[i] * hashCode);
}
}
int GetResult(string &a,string &b){
int n = a.size(),m = b.size();
a.append(b);
vector<long long int> h,p;
Gethash(a,h,p);
int r = a.size(),l = r - m + 1;
int target = int(h[r] - h[l - 1] * p[r - l + 1]);
for(int i = 1;i <= n;i++){
int j = i + m - 1;
int val = int(h[j] - h[i - 1] * p[j - i + 1]);
if(val == target) return i - 1;
}
return -1;
}