KMP

Generally speaking, there are a lot of problems about strings processing. Now you encounter another such problem. If you get two strings, such as “asdf” and “sdfg”, the result of the addition between them is “asdfg”, for “sdf” is the tail substring of “asdf” and the head substring of the “sdfg” . However, the result comes as “asdfghjk”, when you have to add “asdf” and “ghjk” and guarantee the shortest string first, then the minimum lexicographic second, the same rules for other additions.

Input

For each case, there are two strings (the chars selected just form ‘a’ to ‘z’) for you, and each length of theirs won’t exceed 10^5 and won’t be empty.

Output

Print the ultimate string by the book.

Sample Input

asdf sdfg
asdf ghjk

Sample Output

asdfg
asdfghjk

题意就是给两个字符串,求他们相加的结果,要求一个字符串的前缀与另一个字符串的后缀相同时,去除这个相同的然后相加,且最后的总字符串的长度最小。
数据比较大不能同暴力匹配,只能用KMP。

    #include<iostream>
<span style="font-size:18px;">    #include<cstring>
    using  namespace std;
    char S[100005],T[100005];
    int Next[100005];
    void get_next(char *t)//求next数组
    {
        int i=0,j=-1;
        Next[0]=-1;
        int Lt=strlen(t);

        while(i<Lt)
        {
            if(j==-1||t[i]==t[j])
            {
                ++i,++j;
                Next[i]=j;
            }
            else
            j=Next[j];
        }
    }
    int kmp(char *s,char *t)//把t作为模式串,s作为文本串,找到s中的最长后缀与t中的最长前缀的字符在t中的位置j。
    {
        int lens=strlen(s);
        int lent=strlen(t);
        int i=0,j=0;
        get_next(t);
        while(i<lens&&j<lent)
        {
            if(j==-1||s[i]==t[j])
            {
                ++i,++j;
            }
            else
            j=Next[j];
        }
        if(j<lent||j==lent&&i==lens)//s中存在这样的字串或者t为s的字串。
        return j;//匹配串的位置 J

        return -1;
    }
    int main()
    {
        while(cin>>S>>T)
        {

          int lena=kmp(S,T);
          int lenb=kmp(T,S);
          int lT=strlen(T);
          int lS=strlen(S);
         if(lena>lenb||lena==lenb&&strcmp(S,T)<0)//谁的前缀与另一个后缀相同的多,就输出谁,应为要求字符串最短
         {
            cout<<S;
            for(int i=lena;i<lT;i++)//输出T剩下的部分
            {
                cout<<T[i];
            }
            cout<<endl;
        }
        else//同上
        {
            cout<<T;
            for(int i=lenb;i<lS;i++)
            {
                cout<<S[i];
            }
            cout<<endl;
        }
        }
        return 0;
 }

KMP好难不怎么好理解,讲都不怎么好讲,也不知道是怎么想出来的, <img alt="生气" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/mad.gif" />
</span>








 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值