[英]longest palindrome recursive method when two characters at begin and end are equal why do we compare the count with rest of string?
我正在尝试使用递归方法和动态编程来理解 python 中最长回文的解决方案(A-尚未理解为什么我们称之为动态编程)
我了解基本条件
我知道当两个字符相等时,我们会移动到字符串中的下一个字符,即
c=_longestPalen(st, b+1, e-1, c+2)
B-但是我们为什么要这样做
return bigger(c, bigger(_longestPalen(st, b+1,e,c), _longestPalen(st, b, e-1, c)))
这是整个代码
def longestPalen(st):
res=_longestPalen(st, 0,len(st)-1, 0)
return res
def bigger(x, y):
if x>y:
return x
else:
return y
def _longestPalen(st, b,e,c):
if e<b: return c
if b==e: return c+1
if st[b] == st[e]:
c=_longestPalen(st, b+1, e-1, c+2)
return bigger(c, bigger(_longestPalen(st, b+1,e,c), _longestPalen(st, b, e-1, c)))
return bigger(_longestPalen(st, b+1, e, 0), _longestPalen(st, b, e-1, 0))
我稍微重组了代码,使其更符合 Python 约定:
def longest_palen(s):
return _longest_palen(s, 0, len(s) - 1, 0)
def _longest_palen(s, b, e, c):
if e < b:
return c
if b == e:
return c + 1
if s[b] == s[e]:
return max(_longest_palen(s, b + 1, e - 1, c + 2),
_longest_palen(s, b + 1, e, c),
_longest_palen(s, b, e - 1, c))
return max(
_longest_palen(s, b + 1, e, 0),
_longest_palen(s, b, e - 1, 0)
)
if __name__ == '__main__':
print(longest_palen("cyabbaxc")) # abba ("cyabbaxc"[2:6])
print(longest_palen("cabbacxc")) # cabbac ("cabbacxc"[:6])
print(longest_palen("cxcabbac")) # cabbac ("cxcabbac"[2:])
如果当前的第一个和最后一个字符相同,则有四个选项:
你跑步的原因
c = _longestPalen(str, b + 1, e - 1, c + 2)
return bigger(c, bigger(_longestPalen(str, b + 1, e, c), _longestPalen(str, b, e - 1, c)))
或者
return max(_longest_palen(s, b + 1, e - 1, c + 2),
_longest_palen(s, b + 1, e, c),
_longest_palen(s, b, e - 1, c))
在修改后的实现中,就是要考虑所有这些情况。
此行的伪代码类似于:
bigger(both_first_last_included, bigger(only_first_included, only_last_included))
在修改后的实现中,我使用max ,我发现它更清楚地了解正在发生的操作。
max(both_first_last_included, only_first_included, only_last_included)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.