题解 | #最长回文子串#

最长回文子串

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

 # 方法1:中心外扩,遍历s的每个字符,以当前字符作为中心
def fun(s: str, begin: int, end: int):
    while begin >= 0 and end < len(s) and s[begin] == s[end]:
        begin -= 1
        end += 1
    return end - begin - 1

while True:
     try:
        s = input()
        maxlen = 1
        for i in range(len(s) - 1):
		  # 需要考虑回文长度的奇偶性
             maxlen = max(maxlen, max(fun(s, i, i), fun(s, i, i + 1)))
        print(maxlen)
    except:
       break

# 方法2:暴力解决:复杂度高
while True:
    try:
        s = input()
        res = []

        for i in range(len(s)):
            for j in range(i + 1, len(s) + 1):
                if s[i:j] == s[i:j][::-1]:
                    res.append(j - i)
        if res != "":
            print(max(res))
    except:
        break

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务