public class LCS {
public int longestCommonSubsequence(String a, String b){
int[][] temp = new int[a.length()][b.length()];
for(int i = 0 ; i < a.length() ; i++){
for(int j = 0 ; j < b.length() ; j++){
if(a.charAt(i) == b.charAt(j)){
if(i == 0 || j == 0)
temp[i][j] = 1;
else
temp[i][j] = temp[i-1][j-1] + 1;
}else{
if(i == 0 && j == 0)
temp[i][j] = 0;
else if(i == 0 && j != 0)
temp[i][j] = temp[i][j-1];
else if(i != 0 && j == 0)
temp[i][j] = temp[i-1][j];
else
temp[i][j] = Math.max(temp[i-1][j], temp[i][j-1]);
}
}
}
print(temp, a, b);
return temp[a.length() - 1][b.length() - 1];
}
public void print(int[][] temp, String a, String b){
for(int i = 0 ; i < a.length() ; i++){
for(int j = 0 ; j < b.length() ; j++){
System.out.print(temp[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
LCS lcs = new LCS();
int result = lcs.longestCommonSubsequence("abc123ddd129", "234ddd98");
System.out.println(result);
}
}
执行结果
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 2 2 2 2 2 2 2
1 2 2 3 3 3 3 3
1 2 2 3 4 4 4 4
1 2 2 3 4 5 5 5
1 2 2 3 4 5 5 5
1 2 2 3 4 5 5 5
1 2 2 3 4 5 6 6
6