Seek the Name, Seek the Fame

4 篇文章 0 订阅

传送门

   给一个字符串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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GUESSERR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值