一道python面试题: 输出字符串中对称的子字符串的最大长度(最长回文)

举例:
输入cool 则输出2
输入nan 则输出3
输入google 则输出4

直接上代码:

def count_sym(s):
    length = len(s)
    list_s = []
    for i in range(length-1):
        if s[i] == s[i+1]:
            count = 2
            key = 2*i +1
            while i-1 >=0 and key -i+1 <=length-1:
                i = i -1
                if s[i] != s[key-i]:
                    break
                count += 2
            list_s.append(count)
        try:
            if s[i] == s[i+2]:
                count = 3
                key = 2*i + 2
                while i -1 >= 0 and key-i+1 <=length-1:
                    i = i-1
                    if s[i] != s[key-i]:
                        break
                    count += 2
                list_s.append(count)
        except IndexError:
            continue
    return max(list_s)

print(count_sym('0o1o0'))

猜你喜欢

转载自blog.csdn.net/qq_31362767/article/details/82115932