516. Longest Palindromic Subsequence

Link

Solution

定義dp[i][j] : s[i] .... s[j] 的最長palindromic subsequence length

base case: 當 i == j 時,一個字母必定是palindromic,且長度是1

for(int i = 0; i < n; i++){
    dp[i][i] = 1;
}

填入dp[][]:

目標是取得dp[0][n-1]

這裡有點tricky,要從(i, j)之間的distance(dist)開始對i進行looping。

for(int dist = 1; dist < n; dist++){
    for(int i = 0; i + dist < n; i++){
        int j = i + dist;
        dp[i][j] = ...
    }
}

填入時other cases的判斷

if(s[i] == s[j]){
    dp[i][j] = dp[i+1][j-1] + 2
}
else{
    dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
} 
 public int longestPalindromeSubseq(String s) {
        char[] word = s.toCharArray();
        int n = word.length;
        int[][] dp = new int[n][n];
        for(int i = 0; i < n; i++){
            dp[i][i] = 1;
        }
        
        for(int distance = 1; distance < n ; distance++){
            for(int i = 0; i + distance < n; i++){
                int j = i + distance;
                if(word[i] == word[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];
    }

Last updated

Was this helpful?