1040 Longest Symmetric String (25 point(s)) - C语言 PAT 甲级

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/huaxuewan/article/details/101797843

1040 Longest Symmetric String (25 point(s))

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11

题目大意:

给一个字符串,求最大长度的回文字串,输出字串的长度;

设计思路:

思路 1:

  • 遍历字符串:
    • 回文字串是奇数:以当前字符为中心,向两端延伸,判断回文子串长度;
    • 偶数:以当前字符和下一个字符为中心,判断回文字串长度;
  • 时间复杂度:O(n2),最差情况下是 2 * n2

思路 2:动态规划

  • 用二维数组 map[i][j] 记录子串 s[i]…s[j] 是否是回文子串,是记录 1,否记录 0,递推方法:
    • 初始化 map[i][i] = 1,map[i][i + 1] = 1;
    • 当 s[i] == s[j],则 map[i][j] = map[i + 1][j - 1];
    • 当 s[i] != s[j],则 map[i][j] = 0;
  • 每一次外层循环,判断了所有长度为 temp (temp 从 3 递增到 len) 的子串是否是回文串,最终得到回文子串的最大长度;
  • 时间复杂度:O(n2),稳定于 n2 / 2;
  • 此方法来源自柳婼大神,感谢!
编译器:C (gcc)
#include <stdio.h>
#include <string.h>

int main(void)
{
        int map[1001][1001] = {0};
        char s[1001] = {0};
        int max = 1, len, i, j;

        gets(s);
        len = strlen(s);
        for (i = 0; i < len; i++) {
                map[i][i] = 1;
                if (i < len - 1 && s[i] == s[i + 1]) {
                        map[i][i + 1] = 1;
                        max = 2;
                }
        }

        int temp;
        for (temp = 3; temp <= len; temp++) {
                for (i = 0; i + temp - 1 < len; i++) {
                        j = i + temp - 1;
                        if (s[i] == s[j] && map[i + 1][j - 1] == 1) {
                                map[i][j] = 1;
                                max = temp;
                        }
                }
        }
        printf("%d", max);

        return 0;
}

猜你喜欢

转载自blog.csdn.net/huaxuewan/article/details/101797843