|
22 | 22 | */
|
23 | 23 | public class _516 {
|
24 | 24 |
|
25 |
| - /** |
26 |
| - * Inspired by https://discuss.leetcode.com/topic/78603/straight-forward-java-dp-solution |
27 |
| - * dp[i][j] means the longest palindromic subsequence's length of substring(i, j) |
28 |
| - * so, in the end, we return dp[0][s.length() - 1] which means the longest palindromic subsequence |
29 |
| - * of this whole string. |
30 |
| - */ |
31 |
| - public int longestPalindromeSubseq(String s) { |
32 |
| - int[][] dp = new int[s.length()][s.length()]; |
33 |
| - for (int i = s.length() - 1; i >= 0; i--) { |
34 |
| - dp[i][i] = 1;//initialization |
35 |
| - for (int j = i + 1; j < s.length(); j++) { |
36 |
| - if (s.charAt(i) == s.charAt(j)) { |
37 |
| - dp[i][j] = dp[i + 1][j - 1] + 2; |
38 |
| - } else { |
39 |
| - dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); |
| 25 | + public static class Solution1 { |
| 26 | + /** |
| 27 | + * Inspired by https://discuss.leetcode.com/topic/78603/straight-forward-java-dp-solution |
| 28 | + * dp[i][j] means the longest palindromic subsequence's length of substring(i, j) |
| 29 | + * so, in the end, we return dp[0][s.length() - 1] which means the longest palindromic subsequence |
| 30 | + * of this whole string. |
| 31 | + */ |
| 32 | + public int longestPalindromeSubseq(String s) { |
| 33 | + int[][] dp = new int[s.length()][s.length()]; |
| 34 | + for (int i = s.length() - 1; i >= 0; i--) { |
| 35 | + dp[i][i] = 1;//initialization |
| 36 | + for (int j = i + 1; j < s.length(); j++) { |
| 37 | + if (s.charAt(i) == s.charAt(j)) { |
| 38 | + dp[i][j] = dp[i + 1][j - 1] + 2; |
| 39 | + } else { |
| 40 | + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); |
| 41 | + } |
40 | 42 | }
|
41 | 43 | }
|
| 44 | + return dp[0][s.length() - 1]; |
42 | 45 | }
|
43 |
| - return dp[0][s.length() - 1]; |
44 | 46 | }
|
45 |
| - |
46 | 47 | }
|
0 commit comments