Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
网上找了张图挺形象的,我对调了i和j的坐标位置写了一下,挺简单
class Solution: def longestPalindrome(self, s: str) -> str: dp = [[0 for col in range(len(s))] for row in range(len(s))] maxlen = 0 maxlen_i = 0 maxlen_j = 0 for i in range(0,len(s)): for j in range(0,i+1): if i-j < 2 : dp[i][j] = (1 if s[i] == s[j] else 0) else: dp[i][j] = (1 if dp[i-1][j+1] and s[i] == s[j] else 0) if dp[i][j] and maxlen < i-j+1: maxlen = i - j + 1 maxlen_i = i maxlen_j = j return s[maxlen_j:maxlen_i+1] s = Solution() st = "aqsdaba" print(s.longestPalindrome(st))