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")); } }