题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
# https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507?tpId=37&&tqId=21308&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking
# HJ85 最长回文子串
# 描述
# 给定一个仅包含小写字母的字符串,求它的最长回文子串的长度。
# 所谓回文串,指左右对称的字符串。
# 所谓子串,指一个字符串删掉其部分前缀和后缀(也可以不删)的字符串
# (注意:记得加上while处理多个测试用例)
# 输入描述:
# 输入一个仅包含小写字母的字符串
# 输出描述:
# 返回最长回文子串的长度
#author Binqiang Ran
#主要思路就是考虑两种情况‘aba’,'abba',重点就是要注意边界值的问题
#1.当 len(s) >= i+1+n 的时候, s[i+1+n] 可能取不到
def res_substr(s = '',m = 0):
for i in range(1,len(s)-m-1):
#print('i',i,len(s))
gg = True
n = 0
while gg:
if i-n-1 >= 0 and len(s) > i+1+n and s[i-n-1] == s[i+1+n]:
n += 1
else:
gg = False
m = max(n,m)
return m * 2 + 1
def res_substr2(s = '',m = 0):
for i in range(1,len(s)-m-2):
gg, n = True, 0
if s[i] == s[i+1]:
while gg:
if i-n-1 >= 0 and i+2+n < len(s) and s[i-n-1] == s[i+2+n]:
n += 1
else:
gg = False
m = max(n, m)
return 2*m + 2
while True:
try:
s= input()
#s = 'cbdgfgcf'
print(max(res_substr2(s ,m = 0),res_substr(s ,m = 0)))
except:
break
#author Binqiang Ran
#主要思路就是考虑两种情况‘aba’,'abba',重点就是要注意边界值的问题
#相比较上面的方法做了优化,减少了循环次数
# def res_substr(s = '',n = 0):
# for i in range(1,len(s)-n-1):
# #print('i',i,len(s))
# gg = True
# while gg:
# if i-n-1 >= 0 and len(s) > i+1+n and s[i-n-1:i] == s[i+1:i+2+n][::-1]:
# n += 1
# else:
# gg = False
# return n * 2 + 1
# def res_substr2(s = '',n = 0):
# for i in range(1,len(s)-n-2):
# gg = True
# if s[i] == s[i+1]:
# while gg:
# if i-n-1 >= 0 and i+2+n < len(s) and s[i-n-1:i] == s[i+2:i+3+n][::-1]:
# n += 1
# else:
# gg = False
# return 2*n + 2
# while True:
# try:
# s= input()
# #s = 'cbdgfgcf'
# print(max(res_substr2(s ,n = 0),res_substr(s ,n = 0)))
# except:
# break
#借鉴
# while True:
# try:
# s = input()
# m = 0
# for i in range(len(s)):
# if i - m >= 1 and s[i-m-1:i+1] == s[i-m-1:i+1][::-1]:
# m += 2
# elif i - m >= 0 and s[i-m:i+1] == s[i-m:i+1][::-1]:
# m += 1
# if m != 0:
# print(m)
# except:
# break
# 从头到尾扫描字符串,每增加一个新的字符,判断以这个字符结尾,且长度为m+1或m+2的子串是否为回文,
# 如果是,更新最大回文子串 ---> 中心扩散
# i- m >= 1: 防止发生数组越界
# 长度为m+1或m+2的子串: s[i-m-1:i+1] || s[i-m:i+1]
莉莉丝游戏公司福利 690人发布