We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 8c41c84 commit 6d328d0Copy full SHA for 6d328d0
src/com/leetcode/Main516.java
@@ -0,0 +1,34 @@
1
+package com.leetcode;
2
+
3
+/**
4
+ * 516. 最长回文子序列
5
+ * 给定一个字符串 s ,找到其中最长的回文子序列,并返回该序列的长度。可以假设 s 的最大长度为 1000 。
6
+ *
7
8
9
+ * 示例 1:
10
+ * 输入:"bbbab"
11
+ * 输出:4
12
+ */
13
+public class Main516 {
14
+ public int longestPalindromeSubseq(String s) {
15
+ if (s == null || s.length() == 0) {
16
+ return 0;
17
+ }
18
+ int n = s.length();
19
+ int[][] dp = new int[n][n];
20
+ for (int i = 0; i < n; i++) {
21
+ dp[i][i] = 1;
22
23
+ for (int i = n-1; i >=0; i--) {
24
+ for (int j = i+1; j < n; j++) {
25
+ if (s.charAt(i) == s.charAt(j)) {
26
+ dp[i][j] = dp[i+1][j-1] + 2;
27
+ } else {
28
+ dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
29
30
31
32
+ return dp[0][n-1];
33
34
+}
0 commit comments