Home > Software engineering >  Print Longest Palindromic Subsequence
Print Longest Palindromic Subsequence

Time:07-21

I am able to print the length of longest Palindromic subsequence correctly.But i am not able to print the string correctly. Here is the complete question https://leetcode.com/problems/longest-palindromic-subsequence/

Input: s = "bbbab" Output: 4 Explanation: One possible longest palindromic subsequence is "bbbb".

My complete solution is https://leetcode.com/submissions/detail/752148076/

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

Print() function gives output as "bb" for s = "bbbab".Correct would to print 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 );
        

    }

CodePudding user response:

When x is not equal to y, you'll have to add the character twice in the palindrome.

As the palindrome is constructed from the outside inwards, it will be easier to do this with two strings instead of one:

    String left = "", right = "";
    
    while (x < y) { // Treat the case x == y separately
        if (str.charAt(x) == str.charAt(y)) {
            left = left   str.charAt(x);
            right = str.charAt(x)   right;
              x;
            --y;
        } else if (memo[x   1][y] > memo[x][y - 1]) {
              x;
        } else {
            --y;
        }
    }
    if (x == y) { // The middle character
        left = left   str.charAt(x);
    }
    System.out.println("String is "   left   right);

Even better would be to use StringBuffer

  • Related