forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestPalindromicSubsequence.java
64 lines (57 loc) · 1.94 KB
/
LongestPalindromicSubsequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.jwetherell.algorithms.sequence;
/**
* A longest palindromic subsequence is a sequence that appears in the same
* relative order, but not necessarily contiguous(not substring) and
* palindrome in nature.
* <p>
* Given a string, find the length of the longest palindromic subsequence in it.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Longest_palindromic_substring">Longest Palindromic Subsequence (Wikipedia)</a>
* <br>
* @author Miguel Stephane KAKANAKOU <Skakanakou@gmail.com>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class LongestPalindromicSubsequence {
private LongestPalindromicSubsequence() { }
/**
* Find the length of the longest palindromic subsequence in the given
* string s using the dynamic programming approach.
*/
public static int getLongestPalindromeSubsequence(String s) {
if (s == null)
throw new NullPointerException("The given String is null");
final int len = s.length();
final int[][] M = new int[len][len];
final char[] ch = s.toCharArray();
initializeMatrix(M);
fillMatrix(M, ch);
return M[0][len-1];
}
private static void initializeMatrix(int[][] M) {
int len = M.length;
for (int i=0; i<len; i++) {
for (int j=0; j<=i; j++) {
if (j == i)
M[i][j] = 1;
else
M[i][j] = 0;
}
}
}
private static void fillMatrix(int[][] M, char[] ch) {
final int len = M.length;
int i, j;
for (int k=1; k<len; k++) {
i = 0;
j = k;
while (j<len) {
if (ch[i] == ch[j])
M[i][j] = 2 + M[i+1][j-1];
else
M[i][j] = Math.max(M[i][j-1], M[i+1][j]);
i++;
j++;
}
}
}
}