Longest Palindromic Subsequence --> LPS
参考链接
public class LPSTest {
public static void main(String[] args) {
char[] chars = "ABBDCACB".toCharArray();
int length = chars.length;
int result = lps(chars, 0, length - 1);
System.out.println(result);
}
private static int lps(char[] chars, int i, int j) {
//i不断增大,j不断减小,所以当i大于j必须停止递归,然后返回0
if (i > j) {
return 0;
}
if (i == j) {
return 1;
}
if (chars[i] == chars[j]) {
return lps(chars, i + 1, j - 1) + 2;
}
return Math.max(lps(chars, i + 1, j), lps(chars, i, j - 1));
}
}
import java.util.HashMap;
import java.util.Map;
public class LPSTest {
public static void main(String[] args) {
char[] chars = "ABBDCACB".toCharArray();
int length = chars.length;
Map<String, Integer> lookup = new HashMap<>();
int result = lps(chars, 0, length - 1, lookup);
System.out.println(result);
}
private static int lps(char[] chars, int i, int j, Map<String, Integer> lookup) {
//i不断增大,j不断减小,所以当i大于j必须停止递归,然后返回0
if (i > j) {
return 0;
}
if (i == j) {
return 1;
}
String key = i + "|" + j;
if (!lookup.containsKey(key)) {
if (chars[i] == chars[j]) {
lookup.put(key, lps(chars, i + 1, j - 1, lookup) + 2);
} else {
lookup.put(key, Math.max(lps(chars, i + 1, j, lookup), lps(chars, i, j - 1, lookup)));
}
}
return lookup.get(key);
}
}