codeforces1200E. Compress Words——(KMP)

题目链接:https://codeforces.com/contest/1200/problem/E

题目大意:

给你很多个字符串,你需要将字符串合并,如果第一个字符串的后缀与第二个字符串的前缀有匹配的部分,则将两者合并,最后合并的字符串是什么?

思路:

KMP模板题,用第二个串与第一个串中等长后缀进行匹配即可,比如第一个串长度为n,第二个串长度为m,n>m,则从第一个串的n-m处开始与第二个串匹配,最大匹配长度即为可以合并的长度。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;

const int maxn = 1e6 + 10;
int nxt[maxn];
char str[maxn];
char ans[maxn];
int lenn,lenm;
void get_next(){
    int k = -1, j = 0;
    nxt[0] = -1;
    while(j < lenm){
        if(k == -1 || str[j] == str[k]) nxt[++j] = ++k;
        else k = nxt[k];
    }
}
//返回最长匹配长度
int KMP(int pos) {
	get_next();
	int j = 0;
	for (int i = pos; i < lenn; i++) {
		while (j&&ans[i] != str[j])j = nxt[j];
		if (ans[i] == str[j])j++;
		if (j == lenm) {
			return lenm;
		}
	}
	return j;
}
signed main() {
	int N;
	scanf("%d",&N);
	scanf("%s",ans);
	int pos=0;
	lenn=strlen(ans);
	for (int i = 2; i <= N; i++) {
        scanf("%s",str);
        lenm=strlen(str);
        int now=KMP(max(pos-lenm,0));
        for(int j=now;j<lenm;j++){
            ans[lenn++]=str[j];
        }
        pos=lenn;
	}
	for(int i=0;i<lenn;i++){
        printf("%c",ans[i]);
	}
	puts("");
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值