light oj 1258 - Making Huge Palindromes(KMP)

简介: ight oj里这个题目是属于KMP分类的,但乍看好像不是kmp,因为只有一个字符串。要想的到一个回文串,把该字符串翻转接到原串后面必然是一个回文串,但并不一定是最短的。我们必须考虑怎么把两个串尽量融合在一起,这就要看翻转串的前段与原串的后段有多少是匹配的了,这里就用到了KMP算法。

题目链接


题意:


    给你一个字符串,在字符串尾部加上一些字符,使这个字符串变成一个回文串(正反读都一样的字符串),求该回文串的最小长度。


思路:


    在light oj里这个题目是属于KMP分类的,但乍看好像不是kmp,因为只有一个字符串。要想的到一个回文串,把该字符串翻转接到原串后面必然是一个回文串,但并不一定是最短的。我们必须考虑怎么把两个串尽量融合在一起,这就要看翻转串的前段与原串的后段有多少是匹配的了,这里就用到了KMP算法。


代码:

//2013-05-13-20.01
#include <stdio.h>
#include <string.h>
const int maxn = 1000005;
char a[maxn];
char b[maxn];
int f[maxn];
void getfail()
{
    int l = strlen(b);
    f[0] = 0;
    f[1] = 0;
    for (int i = 1; i < l; i++)
    {
        int j = f[i];
        while (j && b[i] != b[j])
            j = f[j];
        if (b[i] == b[j])
            f[i+1] = j+1;
        else
            f[i+1] = 0;
    }
}
int getans()
{
    int la = strlen(a);
    int lb = strlen(b);
    getfail();
    int j = 0;
    for (int i = 0; i < la; i++)
    {
        while (j && a[i] != b[j])
            j = f[j];
        if (b[j] == a[i])
            j++;
    }
    return la + lb - j;
}
int main()
{
    int t;
    scanf("%d", &t);
    for (int i = 1; i <= t; i++)
    {
        scanf("%s", a);
        int l = strlen(a);
        for (int j = 0; j < l; j++)
        {
            b[l-j-1] = a[j];
        }
        b[l] = '\0';
        printf("Case %d: %d\n", i, getans());
    }
    return 0;
}


目录
相关文章
|
7月前
codeforces 317 A Perfect Pair
我先排除了输出-1的,然后再考虑如何计算最小的步数。我们主要在每一步中最小一个加上另一个就可以了,这是朴素的求法,但可能出现这样的情况 比如 -100000000 1 10000000 这样的话会循环100000000多次,肯定超时,所以我们要加快速度。
23 0
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
53 0
LeetCode 241. Different Ways to Add Parentheses
|
Unix Python
LeetCode 71. Simplify Path
给定文件的绝对路径(Unix下的路径)字符串,简化此字符串。
62 0
LeetCode 71. Simplify Path
|
算法 索引
LeetCode 214. Shortest Palindrome
给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
59 0
LeetCode 214. Shortest Palindrome
|
Perl
AtCoder Beginner Contest 217 F - Make Pair (区间dp)
AtCoder Beginner Contest 217 F - Make Pair (区间dp)
94 0
AtCoder Beginner Contest 214 F - Substrings(subsequence DP)
AtCoder Beginner Contest 214 F - Substrings(subsequence DP)
76 0
|
算法 索引
Leetcode-Medium 647. Palindromic Substrings
Leetcode-Medium 647. Palindromic Substrings
102 0
Leetcode-Medium 647. Palindromic Substrings
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
88 0
Leetcode-Easy 20. Valid Parentheses