• PAT甲级:1040 Longest Symmetric String


    题目描述:

    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
    

    代码长度限制

    16 KB

    时间限制

    400 ms

    内存限制

    64 MB

    题目大意: 

    给定一个字符串 求最长回文子串的长度

    解题思路: 

    最长回文子串

    dp[i][j] 表示 s[i] 至 s[j]如果是回文子串则为1, 反之则为0
    1. s[i]==s[j]  那么只需要 s[i+1], s[j-1]是回文子串, s[i]至s[j] 就是回文子串: dp[i][j] = dp[i+1][j-1]

    2. s[i]!=s[j]:
    dp[i][j] = 0    s[i]至s[j]不是回文子串
    根据从边界出发的原理, 注意到边界都是长度为1或2的子串, 每次转移都对子串的长度-1,  dp[i][j] = dp[i+1][j-1]

    不妨考虑按子串的长度和子串的初始位置进行枚举

    Python3代码: 

    1. s = input()
    2. length = len(s)
    3. dp = [[0]*(length+10) for i in range(length+10)]
    4. res = ''
    5. for l in range(1,length+1) :
    6. i = 0
    7. while i + l - 1 < length :
    8. j = i + l - 1
    9. if l == 1 : dp[i][j] = 1
    10. elif l == 2 and s[i] == s[j] : dp[i][j] = 2
    11. else :
    12. if s[i] == s[j] and dp[i+1][j-1] : dp[i][j] = dp[i+1][j-1] + 2
    13. if dp[i][j] > len(res) : res = s[i:j+1]
    14. i += 1
    15. print(len(res))

  • 相关阅读:
    派克Parker直线电机助力锂电池顶盖焊接及叠片设备高效生产
    linux调试技巧
    音乐播放器VHDL蜂鸣器数码管显示简谱,视频/代码
    UE4 GIS Cesium for Unreal插件的使用 教程
    MYSQL---基础篇
    02 【常用类型(上)】
    算法 - 拆炸弹(JavaScript)
    【1024程序员节专访】聚焦行业前沿,共话IT发展趋势
    Python --- 面向对象
    dpi是什么意思
  • 原文地址:https://blog.csdn.net/m0_54689021/article/details/126155322