当前位置 : 主页 > 手机开发 > ROM >

Longest Palindromic Subsequence

来源:互联网 收集:自由互联 发布时间:2021-06-10
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: "

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两个pointer指向的string的一个char, 分别按照相等和不相等来处理即可。

 1 class Solution {
 2     public int longestPalindromeSubseq(String s) {
 3         int length = s.length();
 4         int[][] dp = new int[length][length];
 5         for (int i = 0; i < length; i++) {
 6             dp[i][i] = 1;
 7         }
 8         for (int subLength = 2; subLength <= length; subLength++) {
 9             for (int i = 0; i + subLength <= length; i++) {
10                 int j = subLength + i - 1;
11                 if (s.charAt(i) == s.charAt(j)) {
12                     dp[i][j] = dp[i + 1][j - 1] + 2;
13                 } else {
14                     dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
15                 }
16             }
17         }
18         return dp[0][length - 1];
19     }
20 }
上一篇:leetcode1090
下一篇:两步创建vue全局组件
网友评论