给你一个字符串 s。考虑应用于该字符串的以下算法:
获取字符串的所有前缀,并选择它们之间最长的回文。 如果选择的前缀至少包含两个字符,则从 s 中删除该前缀并使用更新后的字符串返回到第一步。否则,以当前字符串 s 作为结果结束算法。
我失败了这个测试用例“bbabbaabaabbbbb”。我返回“b”而不是“”。我认为正确答案是“b”。但我一定错过了一些东西。
def find(s):
maxLen=0
R=0
L=0
pref=""
for p in range(len(s)):
l=p-1
r=p+1
while l>-1 and r<len(s) and s[r]==s[l]:
if r-l+1>maxLen:
maxLen=r-l+1
R=r
L=l
l-=1
r+=1
l=p
r=p+1
while l>-1 and r<len(s) and s[r]==s[l]:
if r-l+1>maxLen:
maxLen=r-l+1
R=r
L=l
l-=1
r+=1
if R-L+1>1:
return find(s[:L]+s[R+1:])
# return s[:L]+s[R+1:]
else:
return s
x=find(s)
if x:
return x
else:
return ""
既然我得到了你的答案并且我正确地解释了所需的结果,我尝试看看是否可以尝试让你的代码正常工作。尽管我尽了最大的努力,但我还是无法找到解决方案,因此我退后一步来确定程序需要解析并找到给定字符串中最长回文的操作过程。基本上,需要做的是:
因此,这里是执行这些步骤的代码的重构版本。
def IsPalindrome(text): # Simple function to test a string to see if it's a palindrome
result = True
x = len(text)
for i in range(x):
if text[i] != text[x - i - 1]:
result = False
break
return result
def main():
test = input("Enter a string: ") # Acquire the string to evaluate
current = "" # Initialize a string that will hold the largest found palindrome
lenga = len(test)
for ii in range(lenga): # Starting with the complete string, test for the longest palindrome
subs = test[ii:lenga] # Keep decrementing to acquire a shorter substring to test left to right
lengb = len(subs)
for xx in range(1, lengb + 1): # Begin looking for the longest palindrome in each substring
subx = subs[:xx]
if (IsPalindrome(subx)):
if(len(subx) > len(current)): # Compare and store the longest found palindrome
current = subx
print("The longest palindrome found is:", current)
main()
关键是检查字符串是否为回文的函数。这只是实现此目的的众多变体之一。以下是后续对输入的字符串值进行解析并存储找到的最大回文。使用示例字符串测试此代码会产生以下输出。
craig@Vera:~/Python_Programs/LongPal$ python3 LongPal.py
Enter a string: bbabbaabaabbbbb
The longest palindrome found is: bbaabaabb
我希望我没有为你做作业,但已经为你提供了一些解决问题的初步线索。