最长公共子串 子序列 最长回文子串 子序列

最长公共子串 子序列 最长回文子串 子序列

简单易懂的python代码

子串容易输出,子序列比较难(输出str而不是str的长度)

def longestCommonSubstr(self, s, p):  # 为了方便地将短公共子串拓展到长公共子串 必须使用maxEndHere
    if not s or not p:
        return ""
    dp = [[0] * (len(p) + 1) for _ in range(len(s) + 1)]
    res = ""
    for i in range(len(s)):
        for j in range(len(p)):
            if s[i] == p[j]:
                dp[i + 1][j + 1] = 1 + dp[i][j]
                if dp[i + 1][j + 1] > len(res):
                    res = s[i + 1 - dp[i + 1][j + 1]:i + 1]
    return res

def longestCommonSubseq(self, s, p):  # 性质: 串越长,res越大 所以return dp[-1][-1]
    if not s or not p:
        return ""
    dp = [[0] * (len(p) + 1) for _ in range(len(s) + 1)]
    for i in range(len(s)):
        for j in range(len(p)):
            if s[i] == p[j]:
                dp[i + 1][j + 1] = 1 + dp[i][j]
            else:
                dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
    return dp[-1][-1]

def longestPalindromeSubStr(self, s):
    if not s:
        return ""
    dp = [[False] * len(s) for _ in range(len(s))]
    res = ""
    for i in range(len(s), -1, -1):  # 起点
        for j in range(i, len(s)):  # 终点
            if s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1]):
                dp[i][j] = True
            if dp[i][j] and j - i + 1 >= len(res):  # 等长情况下给出第一个子串 需要加上=
                res = s[i:j + 1]
    return res

def longestPalindromeSubSeq(self, s):
    if not s:
        return ""
    dp = [[0] * len(s) for _ in range(len(s))] # dp[i][j]定义的子串s[i:j+1]的最长回文子序列
    for i in range(len(s) - 1, -1, -1): # 地点
        dp[i][i] = 1
        for j in range(i + 1, len(s)): # ij重合的情况跳过
            if s[i] == s[j]:
                dp[i][j] = 2 + dp[i + 1][j - 1]
            else:
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
    return dp[0][-1]

你可能感兴趣的:(最长公共子串 子序列 最长回文子串 子序列)