题解 | #编号子回文II#
编号子回文II
https://www.nowcoder.com/practice/62e2d96d7b534d22a9b754005a4138a5?tpId=354&tqId=10595787&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ public int longestPalindromeSubseq (String s) { // write code here int n = s.length(); int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = 1; } for (int i = 0, j = 1; i < n && j < n; i++, j++) { dp[i][j] = s.charAt(i) == s.charAt(j) ? 2 : 1; } for (int x = 2; x < n; x++) { for (int i = 0, j = x; i < n && j < n; i++, j++) { dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); if (s.charAt(i) == s.charAt(j)) { dp[i][j] = Math.max( dp[i][j], dp[i + 1][j - 1] + 2 ); } } } return dp[0][n - 1]; } }