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
- KMP
- KMP
- KMP
- KMP
- KMP
- KMP
- kmp
- kmp
- KMP
- kmp
- KMP
- KMP
- KMP
- kmp
- KMP
- KMP
- kmp
- KMP
- 若干个vps的速度测试
- 多进程通信 互斥量
- Swiper 3D flow使用方法
- ButterKnife框架问题
- 线程的状态及线程结束时候资源的回收
- KMP
- PHP函数体外的变量无法传入内函数使用原因
- 【功不唐捐,修德为富】创业咨询微访谈实录
- C++学习笔记——sizeof 用法的详细总结及例程
- hdu1542 Atlantis--扫描线
- bootstarp 使用例子~~
- 初学C#的编程小白创建计算器全过程并恶意卖萌(2之增加卖萌元素)
- Petetson算法解决进程竞争问题
- 自己总结的Android开源项目及库(github一个作者的总结)