Compress Words

E. Compress Words

直接套 KMP 即可(那为什么打 cf 的时候没有想到...),求出后一个单词(word)的前缀数组,然后从前面已得的字符串的末尾 - word. length () 开始查询利用前缀数组进行优化即可

代码:

// Created by CAD on 2019/8/12.
#include <bits/stdc++.h>

using namespace std;
using pii=pair<int, int>;
using piii=pair<pair<int, int>, int>;
using ll=long long;

const int maxn=1e6+5;
int nxt[maxn];
void get_next(string s)
{
    int i=0,j=-1;nxt[0]=-1;
    int n=s.length();
    while(i<n)
    {
        if(j==-1||s[i]==s[j])
            nxt[++i]=++j;
        else j=nxt[j];
    }
}
string ans,word;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;cin>>n;
    for(int i=1;i<=n;++i)
    {
        cin>>word;
        int wlen=word.length();
        int alen=ans.length();
        get_next(word);
        int match=0;
        for(int j=max(alen-wlen,0);j<alen;++j)
        {
            while(match>0&&ans[j]!=word[match]) match=nxt[match];
            if(ans[j]==word[match]) match++;
        }
        ans+=word.substr(match);
    }
    cout<<ans<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/CADCADCAD/p/11340824.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值