Skip to content

1682. Longest Palindromic Subsequence II 👍

Approach 1: Top-down

  • Time: $O(26n^2)$
  • Space: $O(26n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int longestPalindromeSubseq(string s) {
    const int n = s.length();
    // dp[i][j][k] := LPS's length in s[i..j] w/ previous char = 'a' + k
    dp.resize(n, vector<vector<int>>(n, vector<int>(27)));
    return lps(s, 0, n - 1, 26);
  }

 private:
  vector<vector<vector<int>>> dp;

  int lps(const string& s, int i, int j, int k) {
    if (i >= j)
      return 0;
    if (dp[i][j][k] > 0)
      return dp[i][j][k];

    if (s[i] == s[j] && s[i] != 'a' + k)
      dp[i][j][k] = lps(s, i + 1, j - 1, s[i] - 'a') + 2;
    else
      dp[i][j][k] = max(lps(s, i + 1, j, k), lps(s, i, j - 1, k));

    return dp[i][j][k];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int longestPalindromeSubseq(String s) {
    final int n = s.length();
    // dp[i][j][k] := LPS's length in s[i..j] w/ previous char = 'a' + k
    dp = new int[n][n][27];
    return lps(s, 0, n - 1, 26);
  }

  private int[][][] dp;

  private int lps(final String s, int i, int j, int k) {
    if (i >= j)
      return 0;
    if (dp[i][j][k] > 0)
      return dp[i][j][k];

    if (s.charAt(i) == s.charAt(j) && s.charAt(i) != 'a' + k)
      dp[i][j][k] = lps(s, i + 1, j - 1, s.charAt(i) - 'a') + 2;
    else
      dp[i][j][k] = Math.max(lps(s, i + 1, j, k), lps(s, i, j - 1, k));

    return dp[i][j][k];
  }
}

Approach 2: Bottom-up

  • Time: $O(26n^2)$
  • Space: $O(26n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int longestPalindromeSubseq(string s) {
    const int n = s.length();
    // dp[i][j][k] := LPS's length in s[i..j] w/ previous char = 'a' + k
    vector<vector<vector<int>>> dp(n, vector<vector<int>>(n, vector<int>(27)));

    for (int d = 1; d < n; ++d)
      for (int i = 0; i + d < n; ++i)
        for (int k = 0; k <= 26; ++k) {
          const int j = i + d;
          if (s[i] == s[j] && s[i] != 'a' + k)
            dp[i][j][k] = dp[i + 1][j - 1][s[i] - 'a'] + 2;
          else
            dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k]);
        }

    return dp[0][n - 1][26];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int longestPalindromeSubseq(String s) {
    final int n = s.length();
    // dp[i][j][k] := LPS's length in s[i..j] w/ previous char = 'a' + k
    int[][][] dp = new int[n][n][27];

    for (int d = 1; d < n; ++d)
      for (int i = 0; i + d < n; ++i)
        for (int k = 0; k <= 26; ++k) {
          final int j = i + d;
          if (s.charAt(i) == s.charAt(j) && s.charAt(i) != 'a' + k)
            dp[i][j][k] = dp[i + 1][j - 1][s.charAt(i) - 'a'] + 2;
          else
            dp[i][j][k] = Math.max(dp[i + 1][j][k], dp[i][j - 1][k]);
        }

    return dp[0][n - 1][26];
  }
}