给一个字符串s,要求s中寻找子串,使得子串既是原串的前缀也是原串的后缀。求满足条件的子串,并其次输出它们。
代码:
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
ll flag[500000];
void GetFlag(string s) {
ll len = s.length();
flag[0] = -1;
flag[1] = 0;
ll i = 1, k = 0;
while (i < len) {
if (k < 0 || s[i] == s[k]) {
flag[++i] = ++k;
}
else {
k = flag[k];
}
}
}
int main() {
FAST_IO;
ll n, m, i, j, k, t;
string s1, s2;
while (cin >> s1 ) {
mes(flag, 0);
GetFlag(s1);
stack<ll>s;
ll f = s1.length()-1;
while (f != -1&&s1[f] == s1[s1.length()-1]) {
s.push(f + 1);
f = flag[f];
}
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
}
}
2020.8.13
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define lp pair<ll, ll>
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
ll n, m, i, j, k, t, flag, x, y, z;
const ll INF = 5e5 + 30;
string s1, s2, s;
ll kmp[INF];
void KMP(string s) {
kmp[0] = -1;kmp[1] = 0;
ll i = 1, k = 0;
while (i < s.length()) {
if (k < 0 || s[i] == s[k])kmp[++i] = ++k;
else k = kmp[k];
}
}
int main() {
FAST_IO;
while (cin >> s) {
KMP(s); i = s.length() - 1;
stack<ll>ss;
while (i != -1 && s[i] == s[s.length() - 1]) {
ss.push(i + 1); i = kmp[i];
}
while (!ss.empty()) {
cout << ss.top() << " ";
ss.pop();
}
cout << endl;
}
}