Python找字符串中的最长回文子串

[本文出自天外归云的博客园]

问题:找出字符串中最长回文子串

我的思路:抛砖引玉。找出所有子串,挨个判断是不是回文,并记录最长的回文子串

代码如下:

#!/usr/bin/python

def is_huiwen(s):
    low, high = 0, len(s)-1
    while low < high:
        if s[low] != s[high]:
            return False
        low += 1
        high -= 1
    return True

def get_longest_huiwen_sub(a):
    sub_longest = ""
    max_length = 0
    for i in range(len(a)):
        for j in range(i, len(a)):
            if j - i + 1 <= max_length:
                continue
            if is_huiwen(a[i:j+1]):
                max_length = len(a[i:j+1])
                sub_longest = a[i:j+1]
    return max_length, sub_longest
                
a= "abccbaab1233245"
max_length, sub_longest = get_longest_huiwen_sub(a)
print(max_length, sub_longest)

 

posted @ 2022-06-28 16:40  天外归云  阅读(290)  评论(0)    收藏  举报