最长回文子序列 可以将输入字符串进行翻转 然后将翻转后的字符串与输入字符串求最长公共子序列就行
public class 最长回文子序列 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = new StringBuffer(s1).reverse().toString(); //字符串翻转
System.out.println(LFH(s1, s2));
}
public static String LFH(String s1, String s2){
int length = s1.length();
int[][] arr = new int[length][length];
int maxLen = 0;
int maxEnd = 0;
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++) {
if (s1.charAt(i) == s2.charAt(j)) {
if (i == 0 || j == 0) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i - 1][j - 1] + 1;
}
} else {
if (i == 0 && j == 0)
arr[i][j] = 0;
else if(i == 0 && j != 0)
arr[i][j] = arr[i][j - 1];
else if(i != 0 && j == 0)
arr[i][j] = arr[i - 1][j];
else
arr[i][j] = arr[i - 1][j] > arr[i][j - 1] ? arr[i - 1][j] : arr[i][j - 1];
}
if (arr[i][j] > maxLen) {
maxLen = arr[i][j];
maxEnd = i; //以 i 位置结尾的字符
}
}
return s1.substring(maxEnd - maxLen + 1, maxEnd + 1); //substring(begin, end) end不包括
}
}