remand = 'abaxyzzyxf' def long_palindrome(s: str) -> str: longest = '' for i in range(len(s)): for j in range(i, len(s)): substr = s[i:j + 1] if is_palindrome(substr) and len(substr) > len(longest): longest = substr return longest def is_palindrome(s: str) -> bool: # low = 0 # high = len(s) - 1 # while low <= high: # if not s[low] == s[high]: # return False # low += 1 # high -= 1 # return True return s == s[::-1] print(long_palindrome(remand)) print(long_palindrome('abc'))
remand = 'abaxyzzyxf' def long_palindrome(s: str) -> str: current = [0, 1] for idx in range(1, len(s)): odd = palindrome(s, idx - 1, idx + 1) even = palindrome(s, idx - 1, idx) long = max(odd, even, key=lambda item: item[1] - item[0]) current = max(current, long, key=lambda item: item[1] - item[0]) return s[current[0]: current[1]] def palindrome(s: str, low: int, high: int) -> tuple[int, int]: length = len(s) while low >= 0 and high < length: if s[low] != s[high]: break low -= 1 high += 1 return low + 1, high print(palindrome(remand, 0, 2)) print(long_palindrome(remand))
标签:子串,palindrome,len,high,item,low,str,最长,回文 From: https://www.cnblogs.com/dissipate/p/16949037.html