1.如果str的最後一個元素和第一個元素是相同的,則有:lps(0,n-1)=lps(1,n-2)+2;例如字元串序列“AABACACBA”,第一個元素和最後一個元素相同,其中lps(1,n-2)表示紅色部分的最長回文子序列的長度;
2.如果str的最後一個元素和第一個元素是不相同的,則有:lps(0,n-1)=max(lps(1,n-1),lps(0,n-2));例如字元串序列“ABACACB”,其中lps(1,n-1)表示去掉第一進制素的子序列,lps(0,n-2)表示去掉最後一個元素的子序列。
傳回最長回文子序列的長度:
package ddd.lps;
public class LPS {
public static void main(String args[]) {
String string = "ACGTGTCAAAATCG";
System.out.println("最長回文子序列長度為:" + lps(string, , string.length() - ));
}
public static int lps(String str, int start, int end) {
if (start == end) {
return ;
}
if (start > end) {
return ;
}
/* 首尾相同時,則首尾是回文子序列的一部分length+2,lps(str, start + 1, end - 1)表示去掉下标為start和end後的字元串進行遞歸的到的最長子序列;*/
if (str.charAt(start) == str.charAt(end)) {
return lps(str, start + , end - ) + ;
} else {
/* 首尾不相同時,lps(str, start + 1, end)表示去掉下标為start後的字元串的最長子序列,lps(str, start, end - 1)表示去掉下标為end後的字元串的最長子序列*/
return max(lps(str, start + , end), lps(str, start, end - ));
}
}
public static int max(int x, int y) {
return (x > y) ? x : y;
}
}
傳回最長回文子序列:
package ddd.lps;
public class LPS2 {
public static void main(String args[]) {
String string = "ACGTGTCAAAATCG";
String result = lps(string, , string.length() - );
System.out.println("最長回文子序列為:" + result);
System.out.println("最長回文子序列的長度為:" + result.length());
}
public static String lps(String str, int start, int end) {
if (start == end) {
return str.charAt(end) + "";
}
if (start > end) {
return "";
}
if (str.charAt(start) == str.charAt(end)) {
return str.charAt(start) + lps(str, start + , end - ) + str.charAt(end);
} else {
String right = lps(str, start + , end);
String left = lps(str, start, end - );
int max = max(left.length(), right.length());
if (max == left.length()) {
return left;
} else {
return right;
}
}
}
public static int max(int x, int y) {
return (x > y) ? x : y;
}
}