[英]how to find the longest palindrome substring when there are two substrings of maximum length
I am solving the longest palindrome substring problem from here . 我从这里开始解决最长的回文字符串问题。 I am stuck on how should I return the substring which occurs first ( with the least starting index ) when there is a conflict. 我陷入困境时应该如何返回首先出现的子字符串(起始索引最少)。
def longestPalindrome(A):
pal_string = ''
x = len(A)
y = 0
for i in range(0,x):
for j in range(x,i-1,-1):
new_str = A[i:j]
if new_str == new_str[::-1]:
if len(new_str) >= y:
y = len(new_str)
pal_string = new_str
return pal_string
print longestPalindrome('abb')
print longestPalindrome('aaaabbaaa')
print longestPalindrome('caba')
print longestPalindrome("abbcccbbbcaaccbababcbcabca")
Input : ("abbcccbbbcaaccbababcbcabca")
should return bbcccbb
but my code returns cbababc
. 输入:( ("abbcccbbbcaaccbababcbcabca")
应该返回bbcccbb
但是我的代码返回cbababc
。
I am using Python2.7. 我正在使用Python2.7。
As @Aran-Fey pointed out, you need to change 正如@ Aran-Fey指出的那样,您需要进行更改
if len(new_str) >= y:
to 至
if len(new_str) > y:
Explanation: If you use the >=
operator, then later palindromes with the same length will override earlier ones, while the >
operator ensures that you will only set pal_string
and y
if you have found a longer palindrome. 说明:如果使用>=
运算符,则具有相同长度的以后的回文将覆盖较早的回文,而>
运算符确保仅在发现更长的回文时才设置pal_string
和y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.