标签:维数 maximum 二维 存储 有一个 nbsp == val div
1 """ 2 Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 3 Example 1: 4 Input: "babad" 5 Output: "bab" 6 Note: "aba" is also a valid answer. 7 Example 2: 8 Input: "cbbd" 9 Output: "bb" 10 """ 11 """ 12 用动态规划做 13 """ 14 class Solution(object): 15 def longestPalindrome(self, s): 16 if s is None: 17 return ‘‘ 18 ret = ‘‘ 19 lens = len(s) 20 max = 0 21 dp = [[0] * lens for i in range(lens)] 22 #产生一个lens*lens全0二维数组,dp数组后面存储True或False 23 for j in range(lens): 24 for i in range(j + 1): 25 dp[i][j] = ((s[i] == s[j]) and (j - i <= 2 or dp[i + 1][j - 1])) 26 #如果s[i]=s[j]说明串的首尾相同, 27 # 并且j-i为0表示只有一个字符必为回文, 28 # j-i=1两个字符切相等必为回文, 29 # j-i=2三个字符首尾相同无论中间是什么必为回文, 30 # 或者dp[i + 1][j - 1]为真表示去掉首尾为回文,而新加的首尾相同必为回文。 31 if dp[i][j] and j - i + 1 > max: 32 max = j - i + 1 33 ret = s[i:j + 1] 34 #表示i开头j结束的串回文并且最长则更新长度max和回文串ret。 35 return ret
leetcode5 Longest Palindromic Substring
标签:维数 maximum 二维 存储 有一个 nbsp == val div
原文地址:https://www.cnblogs.com/yawenw/p/12268859.html