思路:通過一個二維數組存儲兩個字元串的最長公共子序列,int[][] maxLength,一維表示字元串的A的下标,二維表示字元串B的下标,值表示目前下标下的兩個字元串的最長公共長度。
重點:(自己頓悟)
Xi和Yj表示字元串中的元素
maxLength[i][j] = 0; 當i=0或者j=0;
maxLength[i][j] = maxLength[i-1][j-1]+1; 當i>0,j>0&&Xi==Yj;
maxLength[i][j] = max{maxLength[i-1][j],maxLength[i][j-1]} .當i>0,j>0&&Xi!=Yj
import java.util.Stack;
/*
* 最長公共子序列
*/
public class LCSLength {
private int[][] maxLength;//一維:字元串A的下标,字元串B的下标,值:表示目前下标下的兩個字元串的最長公共長度
char[] a;
char[] b;
public LCSLength(String strA,String strB) {
// TODO Auto-generated constructor stub
a=strA.toCharArray();
b=strB.toCharArray();
maxLength=new int[a.length+1][b.length+1];
}
public static void main(String[] args) {
String strA="ABCABDA";
String strB="BADBA";
LCSLength lcsLength = new LCSLength(strA, strB);
lcsLength.getMaxLength();
}
public void getMaxLength(){
for(int i=0;i<maxLength.length;i++){
maxLength[i][0]=0;
}
for(int i=0;i<maxLength[0].length;i++){
maxLength[0][i]=0;
}
//利用動态規劃列出所有的情況
for(int i=1;i<maxLength.length;i++){
for(int j=1;j<maxLength[0].length;j++){
if(a[i-1]==b[j-1]){
maxLength[i][j]=maxLength[i-1][j-1]+1;
}else{
maxLength[i][j]=Math.max(maxLength[i-1][j], maxLength[i][j-1]);
}
}
}
int resultLength=maxLength[a.length][b.length];//最大公共子序列長度
Stack<Character> stack=new Stack<>();
int m=a.length-1;
int n=b.length-1;
while(m>=0&&n>=0){
if(a[m]==b[n]){
stack.push(a[m]);
m--;
n--;
}else if(maxLength[m][n+1]>=maxLength[m+1][n]){//注意,在maxLength中将數+1
m--;
}else{
n--;
}
}
StringBuffer buffer=new StringBuffer();
while(!stack.isEmpty()){
buffer.append(stack.pop());
}
String resultString=buffer.toString();//最長公共自序列
System.out.println(resultLength);
System.out.println(resultString);
}
}