KMP

来源:互联网 发布:天津网络作家排行榜 编辑:程序博客网 时间:2024/05/17 13:10
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 sdfgasdf ghjk

Sample Output

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








 
0 0