#include <iostream>
#include <string>
#include <vector>
using namespace std;
//求next数组
vector<int> Next_arr(const string& s) {
vector<int>v(s.size());
v[0] = -1; //默认v[0] = -1 v[1] = 0
v[1] = 0;
int cur_jump = 0, i = 2; //
while (i < s.size()) {
if (s[i - 1] == s[cur_jump]) {
v[i++] = ++cur_jump;
}
else if (cur_jump > 0) {
cur_jump = v[cur_jump];
}
else {
v[i++] = 0;
}
}
return v;
}
int main()
{
//vector<int>s(9999);
//cout << s.size();
//在str_a里找str_b
string str_a, str_b;
cin >> str_a;
cin >> str_b;
int a_i, b_j;
vector<int>next = Next_arr(str_b);
//int next[str_b.size()];
a_i = b_j = 0;
cout << next.size();
while (b_j<str_b.size()&& a_i < str_a.size()) {
if (str_a.at(a_i) == str_b.at(b_j)) {
a_i++;
b_j++;
}
else if (b_j>0) {
b_j = next[b_j];
}
else {
a_i++;
}
}
cout << "-------------------";
*****//stl提供的kmp算法 直接调用即可 *****
cout << str_a.find(str_b) << endl;
cout<<( b_j == str_b.size() ? a_i - b_j : -1);
return 0;
}
KMP字符串算法
猜你喜欢
转载自blog.csdn.net/qq_42673507/article/details/85231812
今日推荐
周排行