KMP和Manacher
以下代码相关注释未完善,大体内容如下:
代码
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
#define S(X) for (char i : X) {\
std::cout << i;\
}\
class KMP {
public:
KMP() = default;
~KMP() = default;
KMP(const KMP& k) = delete;
KMP(const KMP&& k) = delete;
// 0 1 2 3 4 5 6
// A A B A B A A
// 0 1 0 1 0 1 2
private:
std::vector<int> generate_next(const std::string& str) {
std::vector<int> n(str.size());
for (int i = 1, j = 0; i < str.size(); i++) {
while (str[i] != str[j] && j > 0) {
j = n[j-1];
}
if (str[i] == str[j]) {
n[i] = ++j;
}
}
return n;
}
//std::vector<int> generate_next(const std::string c_pair) {
// int len = c_pair.size();
// std::vector<int> n(len);
// int i = 1, j = 0;
//
// while (i < len) {
// if (c_pair[j] == c_pair[i]) {
// n[i] = j + 1;
// i++;
// j++;
// }
// else if (j == 0) {
// n[i] = 0;
// i++;
// }
// else {
// j = n[j - 1];
// }
// }
//
//
// S;
// return n;
//}
void better_next(std::vector<int>& n, const std::string& c_pair) {
for (int i = 1; i < c_pair.size(); i++) {
if (c_pair[i] == c_pair[n[i]]) {
n[i] = n[n[i]];
}
}
}
public:
std::vector<int> search(const std::string& pair, const std::string& want) {
std::vector<int> next = generate_next(want);
better_next(next, want);
std::vector<int> res;
for (int i = 0, j = 0; i < pair.size(); i++) {
while (j && pair[i] != want[j]) {
j = next[j];
}
if (pair[i] == want[j]) {
j++;
}
if (j == want.size()) {
res.emplace_back(i - j + 1);
j = 0;
}
}
return res;
}
};
class Manacher {
private:
string s, T;
vector<int> P;
void build() {
T = "^#";
for (char c : s) {
T += c;
T += '#';
}
T += '$';
P.assign(T.size(), 0);
int C = 0, R = 0;
for (int i = 1; i < (int)T.size() - 1; ++i) {
int mirror = 2 * C - i;
if (i < R) {
P[i] = min(R - i, P[mirror]);
}
while (T[i + P[i] + 1] == T[i - P[i] - 1]) {
++P[i];
}
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
}
public:
Manacher(const string& str) : s(str) {
build();
}
bool judge(int l, int r) {
if (l > r || l < 0 || r >= (int)s.size()) return false;
int len = r - l + 1;
int center, left_pos = 2 * (l + 1);
if (len % 2 == 1) {
int mid = l + (r - l) / 2;
center = 2 * (mid + 1);
}
else {
int mid_left = l + (r - l) / 2;
center = 2 * (mid_left + 1) + 1;
}
int required = center - left_pos;
return P[center] >= required;
}
};
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
KMP k;
std::vector<int> index = k.search("wworawotaworiooworia", "wori");
for (int i : index) {
std::cout << i << ' ';
}
std::cout << std::endl;
Manacher m;
m.process("wocoeocliefuckkcuf");
std::string_view res_1 = m.judge(3, 5) ? "True" : "False";
std::string_view res_2 = m.judge(2, 6) ? "True" : "False";
std::string_view res_3 = m.judge(2, 7) ? "True" : "False";
std::cout << res_1 << std::endl << res_2 << std::endl << res_3 << std::endl;
return 0;
}

浙公网安备 33010602011771号