题解 | #最长回文子串#

最长回文子串

http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

中心扩展算法

遍历字符串,分别以每个字符为中心,往两边扩展,寻找最长回文子串

中心可能有两种情况:

  • 以单独一个字符为中心进行扩展,针对如‘aba’的字符串
  • 以两个字符为中心,针对如‘abba’的字符串
# 输入字符串
string = input()
maxLength = 0
# 分别以每个字符为中心,向外扩展
for i in range(len(string)):
    # 以一个字符为中心的情况,如'bab'
    step = 0
    while 0 <= i-step and i+step < len(string):
        if string[i+step] == string[i-step]:
            step += 1
        else:
            break
    if step*2-1 > maxLength:
        maxLength = step*2-1
    # 以两个字符为中心的情况,如'baab'
    if i+1 < len(string) and string[i] == string[i+1]:
        step = 0
        while 0 <= i-step and i+1+step < len(string):
            if string[i-step] == string[i+1+step]:
                step += 1
            else:
                break
        if step*2 > maxLength:
            maxLength = step*2
print(maxLength)
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务