美文网首页动态规划
[LeetCode]516. Longest Palindrom

[LeetCode]516. Longest Palindrom

作者: z_star | 来源:发表于2018-12-09 22:19 被阅读12次

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

    Example 1:
    Input:

    "bbbab"
    Output:
    4
    One possible longest palindromic subsequence is "bbbb".
    Example 2:
    Input:

    "cbbd"
    Output:
    2
    One possible longest palindromic subsequence is "bb".

    思路:
    说明

    【基本问题单元的定义】这取决于你所查看问题的角度,找到一个划分,推进问题的角度十分重要。作者找到的方式是dp[ i ][ j ],用来表示 substring( i , j),然后站在这个角度,假设substring(i , j )中的最大的结果是知道的,那么下一步需要确定的是,其如何影响下一个阶段的结果。
    【递推关系】在定义好了基本的问题单元之后,接下来就是用这个定义的单元去表示递推关系。递推关系反映了规模的逐渐扩大。(作者的在处理递推的时候,会选择是以两个字符的方式递推,或者是以一个的方式进行递推)
    【递推的起点】以便其从开始点递推下去。
    【递推的顺序】确定以何种顺序进行递推,这样子才能方便前面计算的结果为后面提供基础,同时避免重复计算。
    (问题单元)dp[i][j]: the longest palindromic subsequence's length of substring(i, j)
    State transition(递推关系):
    dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j)
    otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1])
    (起点)Initialization:dp[i][i] = 1
    但这个思路超时了。。。
    还有最长公共子串参考了下附链接2 manacher
    另外,最长公共子序列,最长公共子串等,待续。。。

    参考:

    1. https://blog.csdn.net/TheSnowBoy_2/article/details/55251028
    2. https://segmentfault.com/a/1190000003914228

    相关文章

      网友评论

        本文标题:[LeetCode]516. Longest Palindrom

        本文链接:https://www.haomeiwen.com/subject/weqlhqtx.html