All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0501_0600.s0516_longest_palindromic_subsequence.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0501_0600.s0516_longest_palindromic_subsequence;

// #Medium #String #Dynamic_Programming #Dynamic_Programming_I_Day_17
// #2022_07_25_Time_88_ms_(58.87%)_Space_68.4_MB_(64.16%)

/**
 * 516 - Longest Palindromic Subsequence\.
 *
 * Medium
 *
 * Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
 *
 * A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
 *
 * **Example 1:**
 *
 * **Input:** s = "bbbab"
 *
 * **Output:** 4
 *
 * **Explanation:** One possible longest palindromic subsequence is "bbbb".
 *
 * **Example 2:**
 *
 * **Input:** s = "cbbd"
 *
 * **Output:** 2
 *
 * **Explanation:** One possible longest palindromic subsequence is "bb".
 *
 * **Constraints:**
 *
 * *   `1 <= s.length <= 1000`
 * *   `s` consists only of lowercase English letters.
**/
public class Solution {
    public int longestPalindromeSubseq(String s) {
        char[] x = s.toCharArray();
        char[] y = new StringBuilder(s).reverse().toString().toCharArray();
        int m = x.length;
        int n = y.length;
        int[][] l = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0) {
                    l[i][j] = 0;
                } else if (x[i - 1] == y[j - 1]) {
                    l[i][j] = l[i - 1][j - 1] + 1;

                } else {
                    l[i][j] = Math.max(l[i - 1][j], l[i][j - 1]);
                }
            }
        }
        return l[m][n];
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy