#python3:注意将c++中带复杂条件的for语句转换为py时,#只能转成while语句来判断条件,在循环外设j初始值,在语句最后j自增classSolution:deflongestPalindrome(self,s:str) ->str: maxLen =0 n =len(s) start =0 end =0for i inrange(n): j =0while i-j >=0and i+j < n and s[i+j]== s[i-j]:if2*j+1> maxLen: start = i-j end = i+j maxLen =2*j+1 j +=1 j =0while i-1-j >=0and i+j < n and s[i-1-j]== s[i+j]:if2*j+2> maxLen: start = i-1-j end = i+j maxLen =2*j+2 j +=1return s[start:end+1]
解法二:DP
dp(i, j) represents whether s(i ... j) can form a palindromic substring, dp(i, j) is true when s(i) equals to s(j) and s(i+1 ... j-1) is a palindromic substring. When we found a palindrome, check if it’s the longest one. Time complexity O(n^2). 需要注意的是构造初始解时,i是从n-1开始,为何?