题解 | #最长回文子串#

最长回文子串

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

def check_one(a, s):
    x1 = a - 1
    y1 = a + 1
    count1 = 1
    while x1 >= 0 and y1 < len(s):
        if s[x1] == s[y1]:
            count1 += 2
            x1 -= 1
            y1 += 1
        else:
            break
    return count1


def check_two(a, b, s):
    count = 0
    if s[a] == s[b]:
        x = a - 1
        y = b + 1
        count += 2
        while x >= 0 and y < len(s):
            if s[x] == s[y]:
                count += 2
                x -= 1
                y += 1
            else:
                break
    else:
        return count
    return count


while True:
    try:
        s1 = input().strip()
        res = 0
        for i in range(0, len(s1) - 1):
            res = max(res, check_one(i, s1), check_two(i, i + 1, s1))

        print(res)
    except:
        break

全部评论
注意对左右两边的数做--和++
点赞 回复 分享
发布于 2024-05-17 22:34 上海

相关推荐

牛客33727151号:不是哥们我以为驾照是段子呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务