标签:style http color os io for ar 代码
题意:给定一个字符串,问需要补上最少的字符使他变成回文串
思路:KMP,把字符串逆序和原串做匹配,匹配到最后一个字符看匹配了多少个,就是最大重合部分,然后相应输出即可
代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXLEN = 100005; struct KMP { int next[MAXLEN]; void getnext(char *str) { int n = strlen(str); next[1] = 0; int j = 0; for (int i = 2; i <= n; i++) { while (j && str[j] != str[i - 1]) j = next[j]; if (str[j] == str[i - 1]) j++; next[i] = j; } } void find(char *T, char *s) { int n = strlen(T); getnext(s); int j = 0; for (int i = 0; i < n; i++) { while (j && T[i] != s[j]) j = next[j]; if (T[i] == s[j]) j++; } printf("%s%s\n", T, s + j); } }; KMP gao; char a[MAXLEN], b[MAXLEN]; int main() { while (~scanf("%s", a)) { strcpy(b, a); reverse(b, b + strlen(b)); gao.find(a, b); } return 0; }
UVA 11475 - Extend to Palindrome(KMP),布布扣,bubuko.com
UVA 11475 - Extend to Palindrome(KMP)
标签:style http color os io for ar 代码
原文地址:http://blog.csdn.net/accelerator_/article/details/38350555