利用动态规划和递归分别求两个串的最大公共子序列
相关代码
/*
* 求两个子串的最大公共子序列
*/
public class Msin {
/*
* 1.利用递归的思想来处理的求最大公共子序列
*/
public static int f(String str, String str2){
if(str.length() == 0 || str2.length() == 0) return 0;
if(str.charAt(0) == str2.charAt(0))
return f(str.substring(1),str2.substring(1)) + 1;
else
return Math.max(f(str.substring(1), str2), f(str, str2.substring(1)));
}
/*
* 2.利用动态规划来解决问题减小了时间复杂度
*/
public static int LCS(String str1, String str2){
int[][] c = new int[str1.length()+1][str2.length()+1]; //建立矩阵
for(int row=0; row<=str1.length(); row++){
c[row][0] = 0;
}
for(int col=0; col<=str2.length(); col++){
c[0][col] = 0;
}
//关键代码
for(int i=1; i<=str1.length(); i++){
for(int j=1; j<=str2.length(); j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
c[i][j] = c[i-1][j-1] + 1;
}else if(c[i][j-1] > c[i-1][j]){
c[i][j] = c[i][j-1];
}else{
c[i][j] = c[i-1][j];
}
}
}
return c[str1.length()][str2.length()];
}
public static void main(String[] args) {
int result = LCS("ABCBDAB", "BDCADA");
System.out.println(result);
}
}