本文共 1208 字,大约阅读时间需要 4 分钟。
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"
思路:以每一个字母为中心,向两边寻找;或者以两个字母为中心向两边寻找。
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ maxi=0 l=0 r=0 def helper(s,l,r): while l>=0 and rmaxi: maxi = length1 l,r=l1,r1 if length2>maxi: maxi = length2 l,r=l2,r2 return s[l:r+1]
第一次写的时候两边界线出错。 在helper写中的是while l>0.这样从第一个字母开始回文就会出错。另外l>=0时,对应最后的s[l+1,r]
还有用dp算法,比较复杂,详情参考
class Solution(object): def longestPalindrome(self, s): if len(s)<2: return s maxlen=0 result='' dp = [[0]*len(s) for i in range(len(s))] for j in range(len(s)): for i in range(j+1): dp[i][j] = (s[i]==s[j]) and (j-i<=2 or dp[i+1][j-1]) if dp[i][j]: if maxlen < j-i+1: maxlen = j-i+1 result = s[i:j+1] return result
转载地址:http://ubrbb.baihongyu.com/