最长回文子串-python
dp方法
def longest_palindrome(s): # input: str output: longest substing # 对于空字符、一个字符,都是其本身 if not s: return '' n = len(s) print(f"字符长度:{n}") # state is_palindrome = [[False]*n for _ in range(n)] for i in range(n): is_palindrome[i][i] = True # 有无必要? # for i in range(1, n): # is_palindrome[i][i-1] = True longest, start, end = 1, 0, 0 # 先循环区间长度,再循环区间起点 for length in range(1, n): print(f"\n区间长度:{length}") for i in range(n-length): j = i + length # 起点i,终点j is_palindrome[i][j] = s[i]==s[j] and is_palindrome[i+1][j-1] print(f"起点:{i}, 终点:{j}, s[i]:{s[i]}, s[j]:{s[j]}, {is_palindrome[i][j]}") if is_palindrome[i][j] and length+1 > longest: longest = length + 1 start, end = i, j return s[start:end+1] longest_palindrome("banana")
时刻记着自己要成为什么样的人!