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

举例:

  • 输入cool 则输出2
  • 输入nan 则输出
  • 输入google 则输出4

代码:

def count_sym(inputS):
    if inputS is None:
        return "输入值不能为None"
    length = len(inputS)
    if length == 0:
        return 0
    list_s = []
    for i in range(length-1):
        if inputS[i] == inputS[i+1]:
            count = 2
            key = 2*i +1
            while i-1 >=0 and key -i+1 <=length-1:
                i = i -1
                if inputS[i] != inputS[key-i]:
                    break
                count += 2
            list_s.append(count)
        try:
            if inputS[i] == inputS[i+2]:
                count = 3
                key = 2*i + 2
                while i -1 >= 0 and key-i+1 <=length-1:
                    i = i-1
                    if inputS[i] != inputS[key-i]:
                        break
                    count += 2
                list_s.append(count)
        except IndexError:
            continue
    return max(list_s)

print(count_sym('happy'))

你可能感兴趣的:(Python,面试相关)