-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestPalindromicSubsequence.java
43 lines (36 loc) · 1.23 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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.HashMap;
import java.util.Map;
// https://leetcode.com/problems/longest-palindromic-subsequence/
public class LongestPalindromicSubsequence {
private final String input;
public LongestPalindromicSubsequence(String input) {
this.input = input;
}
public int solution() {
return calculateLength(input, 0, input.length() - 1, new HashMap<>());
}
private int calculateLength(String s, int start, int end, Map<String, Integer> subs) {
if (start > end) {
return 0;
} else if (start == end) {
return 1;
}
char sChar = s.charAt(start);
char eChar = s.charAt(end);
String key = start + "/" + end;
if (!subs.containsKey(key)) {
int currLength;
if (sChar == eChar) {
currLength = calculateLength(s, start + 1, end - 1, subs) + 2;
} else {
currLength = Math.max(
calculateLength(s, start + 1, end, subs),
calculateLength(s, start, end - 1, subs)
);
}
subs.put(key, currLength);
}
return subs.get(key);
}
}