[DP、ダブルポインタ] 5最長回文サブストリング

文字列sを考えると、秒で最長の回文構造部分文字列を見つけます。あなたは、sの最大の長さが1000であると仮定してもよいです。

例1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
例2:
Input: "cbbd"
Output: "bb"

問題解決のアイデア:

パリンドローム最長の文字列の部分文字列、両手の使用と動的なプログラミングを取得します。Leetcodeと方法:
647:文字列の異なる回文サブストリングの数を見つけます

達成のpython3:

図1に示すように、両手法:
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、動的プログラミング:
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"

ます。https://www.jianshu.com/p/e71c5a055d2aで再現

おすすめ

転載: blog.csdn.net/weixin_33827965/article/details/91203979