Compress Words

思路

用kmp把每一个子串和前面已经处理好的答案串进行匹配,答案串从长度等于子串长度的后缀开始匹配即可,最后得到的子串匹配位置,开始接上答案串Compress Words。

代码

#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;
signed main() {
	int N;
	scanf("%d",&N);
	scanf("%s",ans);
	lenn=strlen(ans);
	for (int i = 2; i <= N; i++) {
        scanf("%s",str);
        lenm=strlen(str);
        int pos=max(0,lenn-lenm);
        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];
        }
    	j = 0;
    	for (int i = pos; i < lenn; i++) {
    		while (j&&ans[i] != str[j])j = nxt[j];
    		if (ans[i] == str[j])j++;
    	}
        for(;j<lenm;j++){
            ans[lenn++]=str[j];
        }
        pos=lenn;
	}
	for(int i=0;i<lenn;i++){
        printf("%c",ans[i]);
	}
	puts("");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值