Longest Palindromic Subsequence LeetCode solution in Java

1
class Solution {
2
public int longestPalindromeSubseq(String s) {
3
StringBuilder sb = new StringBuilder(s);
4
sb.reverse();
5
String s2 = sb.toString();
6
return longestCommonSubsequence(s, s2);
7
}
8

9
public int longestCommonSubsequence(String text1, String text2) {
10
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
11
for (int i = text1.length() - 1; i >= 0; i--) {
12
for (int j = text2.length() - 1; j >= 0; j--) {
13
char ch1 = text1.charAt(i);
14
char ch2 = text2.charAt(j);
15
if (ch1 == ch2) // diagnal
16
dp[i][j] = 1 + dp[i + 1][j + 1];
17
else // right,down considering not matchning char from s1 and skipping s2
18
// considering not matchning char from s2 and skipping s1
19
dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]);
20
}
21
}
22
return dp[0][0];
23
}
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0