LightOJ - Making Huge Palindromes(KMP&回文)

题目链接:http://lightoj.com/volume_showproblem.php?problem=1258
Time Limit: 1 second(s) Memory Limit: 32 MB

Problem Description

A string is said to be a palindrome if it remains same when read backwards. So, 'abba', 'madam' both are palindromes, but 'adam' is not.

Now you are given a non-empty string S, containing only lowercase English letters. The given string may or may not be palindrome. Your task is to make it a palindrome. But you are only allowed to add characters at the right side of the string. And of course you can add any character you want, but the resulting string has to be a palindrome, and the length of the palindrome should be as small as possible.

For example, the string is 'bababa'. You can make many palindromes including

bababababab

babababab

bababab

Since we want a palindrome with minimum length, the solution is 'bababab' cause its length is minimum.

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case starts with a line containing a string S. You can assume that 1 ≤ length(S) ≤ 106.

Output

For each case, print the case number and the length of the shortest palindrome you can make with S.

Sample Input

4
bababababa
pqrs
madamimadam
anncbaaababaaa

Output for Sample Input

Case 1: 11
Case 2: 7
Case 3: 11
Case 4: 19

Note

Dataset is huge, use faster I/O methods.

Problem solving report:

Description: 可在右侧添加若干字母使这个字符串回文,求最终的最短回文串长度。
Problem solving: 首先原串+翻转过来的串必然是一个回文串,但是二者在中间可以“融合”,而KMP算法恰好可以求出最大融合长度。所以看翻转过来的串能匹配多少原串即可,答案就是len+(len-匹配个数)。

Accepted Code:

/* 
 * @Author: lzyws739307453 
 * @Language: C++ 
 */
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
int nex[MAXN];
char sa[MAXN], sb[MAXN];
void Get_Next(char str[], int len) {
    int i = 0, j = -1;
    nex[0] = -1;
    while (i < len) {
        if (~j && str[i] != str[j])
            j = nex[j];
        else nex[++i] = ++j;
    }
}
int KMP(char sa[], char sb[], int len) {
    Get_Next(sb, len);
    int i = 0, j = 0;
    while (i < len) {
        if (~j && sa[i] != sb[j])
            j = nex[j];
        else i++, j++;
    }
    return j;
}
int main() {
    int t, len, kase = 0;
    scanf("%d", &t);
    while (t--) {
        scanf("%s", sa);
        strcpy(sb, sa);
        len = strlen(sa);
        reverse(sb, sb + len);
        printf("Case %d: %d\n", ++kase, (len << 1) - KMP(sa, sb, len));
    }
    return 0;
}
上一篇:判断回文字符串


下一篇:Leetcode-5150 Longest Chunked Palindrome Decomposition(段式回文)