acdream 1722(最长回文子串)

来源:互联网 发布:淘宝退货时间规定 编辑:程序博客网 时间:2024/05/21 02:20

题意:
Problem Description

正如大家知道的,女神喜欢字符串,而在字符串中,女神最喜欢回文字符串,但是不是所有的字符串都是回文字符串,但是有一些字符串可以进行“求导”来变成回文字符串。
字符串中只包含小写字母。
求导过程如下,C++:

string dif(const string x){    if(x.length()<=1)        return "";    string res="";    for(int i=1;i<x.length();++i)        res+=abs(x[i]-x[i-1])+'a';    return res;}

C:

void dif(char*x,char*res)//注意有可能会溢出{    if(x[0]==0||x[1]==0)    {        res[0]=0;        return;    }    int len=1;    for(int i=1;x[i];++i,++len)        res[i-1]=abs(x[i]-x[i-1])+'a';    res[len-1]=0;}

例如”aa”的导字符串是“a”,”aab“的导字符串是”ab”,”aacfwssg”的导字符串是”acdream”。
那么给定一个字符串,请判断在它各阶导字符串中,最长的回文子串是多长?
二阶导字符串即为导字符串的导字符串。
n阶导字符串即为n-1阶导数的导字符串。
Input

多组数据,每组数据包括一个字符串s(1<=|s|<=1000)
Output

对于每组数据,输出一个整数
Sample Input

abcd
abcba
acdream
Sample Output

3
5
3
Hint

样例一,求一次导字符串后为”aaa“,最长回文子串就是本身,所以长度为3
样例二,本身就是回文串,因此,输出本身长度即可
样例三,acdream->cbonem->bnbji->mmib->aeh->ed->b
最长回文串长度分别为1,1,3,2,1,1,1,因此输出3

题解:将字符串循环带入dif函数得到新串,把新串放到求最长回文子串函数求长度,输出最大长度。

#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;const int N = 1005;int solve(char* str) {    int res = 0, len = strlen(str);    for (int i = 1; str[i]; i++) {        int s = i, e = i;        while (str[s] == str[e + 1])            e++;        i = e;        while (str[s - 1] == str[e + 1]) {            s--;            e++;        }        res = max(res, e - s + 1);    }    return res;}void dif(char* x,char* res)//注意有可能会溢出{    if(x[0]==0||x[1]==0)    {        res[0]=0;        return;    }    int len=1;    for(int i=1;x[i];++i,++len)        res[i-1]=abs(x[i]-x[i-1])+'a';    res[len-1]=0;}int main() {    char str[N], res[N];    str[0] = '$';    res[0] = '$';    while (scanf("%s", str + 1) != EOF) {        int ans = solve(str);        while (strlen(str + 1) > 1) {            dif(str + 1, res + 1);            ans = max(ans, solve(res));            strcpy(str + 1, res + 1);            if (strlen(str + 1) <= ans)                break;        }        printf("%d\n", ans);    }    return 0;}
0 0
原创粉丝点击