UVA11475 - Extend to Palindrome

做了好多的kmp题了(其实不多…也就8,9道…)
然后好几个都是没地方想的,我都整理下来了,算了算这是第3个了。

这个字符串成环的比较简单,知道思路就很容易写出来了,关键是思路啊…我这脑子就是想不起来,可能仔细想想可能会想起来的。

其次什么哈希表啥的,可能会做的快。但是我不会啊!
所以,我会的也就是KMP。然后倒置匹配返回结束的位置。我就不细解释了,仔细看代码会看懂的。

哦,对了,其中用到了一个函数,reverse(反向)具体真么用看一下链接:
https://blog.csdn.net/qq_40828914/article/details/81138117
下面是代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>

using namespace std;

#define maxn 100000+66
int Next[maxn];
char s[maxn], t[maxn];
int len;

void getNext(char *t){

    int i = 0,j = -1;
    Next[0] = -1;
    while(i < len){
        if(j == -1 || t[i] == t[j]){
            Next[i+1] = j+1;
            i++;
            j++;
        }
        else  j = Next[j];
    }
    return;
}

int KMP(char *s, char *t){

    int i = 0, j = 0;
    while(i < len){
        if(j == -1|| s[i] == t[j]){
            i++; j++;
        }
        else j = Next[j];
    }
    return j;
}

int main(){

    while(scanf("%s",s) != EOF){
        len = strlen(s);
        strcpy(t,s);
        reverse(t+0,t+len);
        getNext(t);
        cout << s << t+KMP(s,t) << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44031744/article/details/86693662
今日推荐