A + B for you again hdu1867(KMP的应用)

   

A + B for you again


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
题意:连个字符串相加,要求如果a的后缀和b的前缀匹配,就只输出一个,即重合,要求第一输出的字符串最短,其次按照字典序输出 思路:其实这是一道很好的KMP的应用及其变形,kmp算法是查找一个目标字符串中的模板串,而这道题并没有让我们去查找是否含有模板串,而是去找后缀的匹配长度,实际上仍然是使用kmp算法,让kmp算法整个循环结束最后返回最后的下一次要查找的坐标就可以,实际就是Next[i]的值,就是末尾已经匹配好的长度,比较两次选出最短的就可以了 code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int Next[100100];
char s1[100100],s2[100100];
void getNext(char s[]){
    int i,j;
    i = -1;
    j = 0;
    memset(Next,0,sizeof(Next));//先初始化一下Next数组
    Next[0] = -1;
    int lens = strlen(s);
    while(j < lens){
        if(i==-1||s[i]==s[j]){
            i++,j++;
            if(s[i]==s[j]) Next[j] = Next[i];
            else Next[j] = i;
        }
        else i = Next[i];
    }

}
int Kmp(char s[],char m[]){//s是目标字符串,m是模板字符串
    int i = 0,j = 0;
    int lens = strlen(s);
    getNext(m);
    while(j < lens){
        if(i==-1||m[i]==s[j]){
            i++,j++;
        }
        else i = Next[i];
    }
    return i;//实际上这道题并不是让我们找目标字符串中是否含有模板串,而是在后缀中找到相匹配的,所以一路循环到最后得到的i就是相应的目标串中后缀和模板相匹配的长度
}
int main(){
    while(~scanf("%s%s",s1,s2)){
        //分别求两边,看谁当目标串的时候后缀能匹配的最长
        int str1 = Kmp(s1,s2);//s1当目标,s2当模板
        int str2 = Kmp(s2,s1);//s2当目标,s1当模板
        if(str1==str2){//如果相同,那么按字典序顺序
            if(strcmp(s1,s2)<0)printf("%s%s\n",s1,str1+s2);//s2字符串字典序大,先输出s1,然后从str1位置开始输出字符串s2,因为前面的是匹配的
            else printf("%s%s\n",s2,str1+s1);//同理
        }
        else if(str1>str2){
            printf("%s%s\n",s1,str1+s2);//s1后缀匹配的长,先输出s1,然后从s2的str1位置开始输出s2
        }
        else printf("%s%s\n",s2,str2+s1);//s2后缀匹配长,先输出s2,然后从s1的str2位置开始输出s1
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值