返回介绍

solution / 0500-0599 / 0516.Longest Palindromic Subsequence / README_EN

发布于 2024-06-17 01:03:59 字数 3414 浏览 0 评论 0 收藏 0

516. Longest Palindromic Subsequence

中文文档

Description

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.

Solutions

Solution 1

class Solution:
  def longestPalindromeSubseq(self, s: str) -> int:
    n = len(s)
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
      dp[i][i] = 1
    for j in range(1, n):
      for i in range(j - 1, -1, -1):
        if s[i] == s[j]:
          dp[i][j] = dp[i + 1][j - 1] + 2
        else:
          dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
    return dp[0][-1]
class Solution {
  public int longestPalindromeSubseq(String s) {
    int n = s.length();
    int[][] dp = new int[n][n];
    for (int i = 0; i < n; ++i) {
      dp[i][i] = 1;
    }
    for (int j = 1; j < n; ++j) {
      for (int i = j - 1; i >= 0; --i) {
        if (s.charAt(i) == s.charAt(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];
  }
}
class Solution {
public:
  int longestPalindromeSubseq(string s) {
    int n = s.size();
    vector<vector<int>> dp(n, vector<int>(n, 0));
    for (int i = 0; i < n; ++i) {
      dp[i][i] = 1;
    }
    for (int j = 1; j < n; ++j) {
      for (int i = j - 1; i >= 0; --i) {
        if (s[i] == s[j]) {
          dp[i][j] = dp[i + 1][j - 1] + 2;
        } else {
          dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
        }
      }
    }
    return dp[0][n - 1];
  }
};
func longestPalindromeSubseq(s string) int {
  n := len(s)
  dp := make([][]int, n)
  for i := 0; i < n; i++ {
    dp[i] = make([]int, n)
    dp[i][i] = 1
  }
  for j := 1; j < n; j++ {
    for i := j - 1; i >= 0; i-- {
      if s[i] == s[j] {
        dp[i][j] = dp[i+1][j-1] + 2
      } else {
        dp[i][j] = max(dp[i+1][j], dp[i][j-1])
      }
    }
  }
  return dp[0][n-1]
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文