# Leetcode 516. Longest Palindromic Subsequence

Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.

找到一个字符串的最长回文子序列，这里注意回文子串和回文序列的区别。子序列不要求连续，子串（substring）是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。

思路很简答，其实最长回文子序列就是字符串本身和其翻转字符串的最长公共子序列，求两个字符串的最长公共子序列其实是动态规划入门题目。 题解代码如下。

public class Solution {
public int longestPalindromeSubseq(String s) {
StringBuffer tmp = new StringBuffer(s);
String t = tmp.reverse().toString();
int[][] dp = new int[s.length()+1][s.length()+1];
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(i) == t.charAt(j)) {
dp[i+1][j+1] = dp[i][j]+1;
}
else {
dp[i+1][j+1] = Math.max(dp[i][j+1], dp[i+1][j]);
}
}
}
return dp[s.length()][s.length()];
}
public static void main(String[] args) {
Solution s= new Solution();
System.out.println(s.longestPalindromeSubseq("bbbab"));
}
}

|
10月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters

41 3
LeetCode 424. Longest Repeating Character Replacem

97 0
LeetCode 409. Longest Palindrome

67 0
LeetCode 395. Longest Substring with At Least K

76 0
|

LeetCode 392. Is Subsequence

93 0
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
76 0
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III

38 6
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 26. 树的子结构

34 4
|
1月前
|

【Leetcode刷题Python】牛客. 数组中未出现的最小正整数

65 2
|
1月前
|

【Leetcode刷题Python】从列表list中创建一颗二叉树

32 7