前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【DP、双指针】5. Longest Palindromic Substring

【DP、双指针】5. Longest Palindromic Substring

作者头像
echobingo
发布2019-06-13 16:17:05
5290
发布2019-06-13 16:17:05
举报

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:
代码语言:javascript
复制
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
代码语言:javascript
复制
Input: "cbbd"
Output: "bb"
解题思路:

找一个字符串的最长回文子串,可以使用双指针法和动态规划法。方法同 Leetcode:

647:求一个字符串的不同回文子串个数

Python3 实现:
1、双指针法:
代码语言:javascript
复制
class Solution:
    # 方法1:分奇回文串和偶回文串
    def longestPalindrome(self, s: str) -> str:
        if s == "":
            return ""
        lens = len(s)
        maxl = 1
        maxs = s[0]
        for i in range(len(s)):
            es = self.find(s, lens, i, i+1)
            os = self.find(s, lens, i, i+2)
            if len(es) > maxl:
                maxl = len(es)
                maxs = es
            if len(os) > maxl:
                maxl = len(os)
                maxs = os
        return maxs

    def find(self, s, lens, i, j):
        while i >= 0 and j < lens and s[i] == s[j]:
            i -= 1
            j += 1
        return s[i+1:j]

print(Solution().longestPalindrome("aaa")) # "aaa"
2、动态规划法:
代码语言:javascript
复制
class Solution:
    # 方法2:dp[i][j] = True if dp[i+1][j-1] == True and s[i] == s[j]
    def longestPalindrome(self, s: str) -> str:
        if s == "":
            return ""
        lens = len(s)
        maxl = 1
        maxs = s[0]
        dp = [[False] * lens for _ in range(lens)]
        for j in range(lens):
            dp[j][j] = True
            for i in range(j-1, -1, -1):
                if i+1 <= j-1 and dp[i+1][j-1] and s[i] == s[j]:  # 奇回文串
                    dp[i][j] = True
                elif i+1 > j-1 and s[i] == s[j]:  # 偶回文串
                    dp[i][j] = True
                # 如果是回文串,更新最大长度
                if dp[i][j] and j-i+1 > maxl:
                    maxl = j-i+1
                    maxs = s[i:j+1]
        return maxs

print(Solution().longestPalindrome("babad")) # "bad"
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.06.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • 解题思路:
  • Python3 实现:
    • 1、双指针法:
      • 2、动态规划法:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档