Compress Words(前后缀匹配->kmp算法)

题目

Amugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn’t like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges “sample” and “please” into “samplease”.

Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.

题意

输入n个词,希望将它们从左往右压缩成一个词(首先合并前两个单词,然后将结果与第三个单词合并,依此类推)
两个单词合并时要求删除第二个单词中与第一个单词后缀重合的最长前缀

思路

典型的字符串前后缀匹配问题,我们可以直接代入kmp模板求解.注意每次匹配结束后要更新被匹配的字符串

代码如下

#include <iostream>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
char b[1000005], a[1000005]; int n, m, x,nex[1000005];
int main()
{
    cin >> x;
    cin >> b; cout << b; m = strlen(b);
    while (x--) {
        cin >> a; 
        n = strlen(a);
        nex[1] = 0;
        int N ;
        //字符串a的自匹配
        for (int i = 2, j = 0; i <= n; i++) {
            while (j > 0 && a[i-1] != a[j]) j = nex[j];
            if (a[i-1] == a[j]) j++;
            nex[i] = j;
        }
        //匹配字符串a与b
        for (int i = max(1,m-n+1), j = 0; i <= m; i++) {
            while (j > 0 && (j == n || b[i-1] != a[j])) j = nex[j];
            if (b[i-1] == a[j]) j++; 
            //最后所得的N值即为前后缀最大匹配长度
            N = j;
        }
        //输出非字符串a的"重复"部分,并将字符串a,b进行去"重复"的合并
        for (int i = N; i < n; i++) cout << a[i], b[m + i - N] = a[i];
        //更新新字符串长度
        m += n - N;
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值