Skip to content

Commit e26aee5

Browse files
refactor 516
1 parent 353dc7b commit e26aee5

File tree

2 files changed

+22
-21
lines changed

2 files changed

+22
-21
lines changed

src/main/java/com/fishercoder/solutions/_516.java

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -22,25 +22,26 @@
2222
*/
2323
public class _516 {
2424

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+
}
4042
}
4143
}
44+
return dp[0][s.length() - 1];
4245
}
43-
return dp[0][s.length() - 1];
4446
}
45-
4647
}

src/test/java/com/fishercoder/_516Test.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,19 @@
44
import org.junit.BeforeClass;
55
import org.junit.Test;
66

7-
import static junit.framework.Assert.assertEquals;
7+
import static org.junit.Assert.assertEquals;
88

99
public class _516Test {
10-
private static _516 test;
10+
private static _516.Solution1 solution1;
1111

1212
@BeforeClass
1313
public static void setup() {
14-
test = new _516();
14+
solution1 = new _516.Solution1();
1515
}
1616

1717
@Test
1818
public void test1() {
19-
assertEquals(4, test.longestPalindromeSubseq("bbbab"));
19+
assertEquals(4, solution1.longestPalindromeSubseq("bbbab"));
2020
}
2121

2222
}

0 commit comments

Comments
 (0)