【问题标题】:Print Longest Palindromic Subsequence打印最长回文子序列
【发布时间】:2022-07-21 00:31:17
【问题描述】:

我能够正确打印最长回文子序列的长度。但我无法正确打印字符串。 这是完整的问题 https://leetcode.com/problems/longest-palindromic-subsequence/

输入:s = "bbbab" 输出:4 解释:一个可能的最长 回文子序列是“bbbb”。

我的完整解决方案是https://leetcode.com/submissions/detail/752148076/

      print(s); //print the solution .But doesnt give correct answer.Below is the code snippet.

Print() 函数将 s = "bbbab" 的输出作为 "bb"。正确的会打印 bbbb

//use this function for printing dp array!
    public void print(String str) {
       
        int x = 0,
        y = str.length() - 1; 
     //   int ans=4;
        String palindromicSubsequence="";
        
        while (x <= y) {
            if (str.charAt(x) == str.charAt(y)) {
               palindromicSubsequence= palindromicSubsequence + str.charAt(x);
                 ++x;
                --y;
            } else if ( memo[x + 1][ y] > memo[x][y - 1] ) {
                ++x;
            } else {
                --y;
            }
                
        }
            System.out.println("String is " + palindromicSubsequence );
        

    }

【问题讨论】:

    标签: algorithm recursion data-structures dynamic-programming


    【解决方案1】:

    x 不等于y 时,您必须在回文的两边 附加字符:

    palindromicSubsequence = (x < y ? str.charAt(x) : "") 
                           + palindromicSubsequence + str.charAt(x);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2021-12-29
      • 2017-02-25
      • 2012-09-07
      相关资源
      最近更新 更多