首页 > 试题广场 >

回文串

[编程题]回文串
  • 热度指数:533 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

回文串是指字符串无论从左读还是从右读,所读的顺序是一样的;简而言之,回文串是左右对称的。

现给定一个字符串,求出它的最长回文子串。你可以假定只有一个满足条件的最长回文串。


输入描述:
一行, 字符串


输出描述:
一行, 字符串
示例1

输入

yabccbau

输出

abccba
s=input().strip()
t=[]
for i in range(len(s)):
    j=i-1
    k=i+1
    tmp=[]
    tmp.append(s[i])
    while j>=0 and k<len(s) and s[j]==s[k]: 
        tmp.insert(0,s[j])
        tmp.append(s[k])
        j=j-1
        k=k+1
    if len(tmp)>len(t):t=tmp
    j=i
    k=i+1
    tmp=[]    
    while j>=0 and k<len(s) and s[j]==s[k]:
        tmp.insert(0,s[j])
        tmp.append(s[k])
        j=j-1
        k=k+1
    if len(tmp)>len(t):t=tmp
tt=""
for i in range(len(t)):
    tt+=t[i]
print(tt)

发表于 2021-05-24 19:20:29 回复(0)