题解 | #最长回文子串#

最长回文子串

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

while 1:
    try:
        s = input().strip()
        li = []  # 创建空列表用于储存所遍历过的字符串,并用于回文匹配
        c = 0  # 初始化回文长度
        cl = []  # 创建空列表用于储存各回文长度
        for i, v in enumerate(s):  # 对字符串进行遍历并附带索引值
            # print(i ,s[i])
            if li:  # 列表内有值,无值则添加遍历值
                index2 = i  # 初始化顺序索引,用于向前匹配字符
                if v == li[-1]:  # 回文长度为偶数时
                    index1 = -1  # 初始化逆序索引,用于向后匹配字符
                    while li[index1] == s[index2]:  # 当前后匹配字符相等时执行循环
                        c += 2  # 回文长度+2
                        index1 -= 1  # 从已遍历列表中后移一位
                        index2 += 1  # 从未遍历的字符串中后移一位
                        if index1 < -len(li) or index2 >= len(s):  # 逆序索引或顺序索引超出范围时跳出循环
                            break
                if c:  # 储存非0长度的回文长度
                    cl.append(c)
                c = 0  # 回文长度归零
                if i + 1 < len(s):  # 索引不可超出最大范围
                    if s[i + 1] == li[-1]:  # 回文长度为奇数时,注意此处不可用elif,奇偶情形会同时出现,例如aaaa的回文长度会计算多次:2、3、4、3、2
                        index1 = -1  # 初始化逆序索引,重新设置为-1
                        index2 = i + 1  # 初始化顺序索引,即为当前遍历值的下一值的索引
                        c += 1  # 初始回文长度为1
                        # print(index1, index2)
                        # print(li[index1], s[index2])
                        while li[index1] == s[index2]:  # 当前遍历值的前后值对比,下面同上理
                            c += 2
                            index1 -= 1
                            index2 += 1
                            if index1 < -len(li) or index2 >= len(s):
                                break
                    if c:
                        cl.append(c)
                    c = 0
                li.append(v)  # 将遍历值添加进列表中
            else:
                li.append(v)
        print(max(cl))  # 输出最大回文长度
    except:
        break

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务