516. Longest Palindromic Subsequence
来源:互联网 发布:阿里巴巴 淘宝 便宜 编辑:程序博客网 时间:2024/06/05 15:11
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.
- Example 1:
Input:
"bbbab"
Output:4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:“cbbd”
Output: 2
One possible longest palindromic subsequence is “bb”.
题目大意:给定一个字符串,找出字符串中最长的回文子串
思路:DP dp[i][j]表示i到j范围最长的回文串 状态转移方程
dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j)otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1])
代码
package DP;/*** @author OovEver* 2017/12/25 11:03*/public class LeetCode516 { public int longestPalindromeSubseq(String s) {// dp[i][j]表示i到j范围最长的回文串// dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j)// otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]) int[][] dp = new int[s.length()][s.length()]; for(int i=s.length()-1;i>=0;i--) { dp[i][i] = 1; for(int j=i+1;j<s.length();j++) { 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][s.length() - 1]; }}
阅读全文