LeetCode——516. The longest palindrome subsequence

Title description:

Given a string s, find the longest palindrome subsequence, and return the length of the sequence. It can be assumed that the maximum length of s is 1000.

prompt:

  • 1 <= s.length <= 1000
  • s contains only lowercase English letters

Example 1:
Input:
"bbbab"
Output:
4
The longest possible palindrome subsequence is "bbbb".

Example 2:
Input:
"cbbd"
Output:
2
The longest possible palindrome subsequence is "bb".

Problem-solving ideas:

  • The state f[i][j] indicates the length of the longest palindrome sequence in the substring composed of the ith character to the jth character of s
  • Transfer equation
    If the ith character of s and the jth character are the same, then f[i][j] = f[i + 1][j-1] + 2
    If the ith character of s is different from the jth character If f[i][j] = max(f[i + 1][j], f[i][j-1])
  • Then pay attention to the traversal order, i traverses from the last character forward, and j traverses from i + 1 backwards, so as to ensure that each sub-problem has been calculated.
  • Initialize f[i][i] = 1 The longest palindrome sequence of a single character is 1
  • Result f[0][n-1]

The JAVA code is as follows:

class Solution {
    
    
    public int longestPalindromeSubseq(String s) {
    
    
        int n = s.length();
        char[] ch = s.toCharArray();
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
    
    
            dp[i][i] = 1;
        }
        for (int i = n - 2; i >= 0; i--) {
    
    
            for (int j = i + 1; j < n; j++) {
    
    
                if (ch[i] == ch[j]) {
    
    
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
    
    
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[0][n-1];
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/113432891