您的位置:首页 > 其它

找两个字符串的最长公共子序列的长度

2012-10-21 23:57 190 查看
简述:

找两个字符串的最长公共子序列的长度

例如

String str1 = “caaac”;

String str2 = "bbdaaaca";

两者最长公共子序列就是aaac 为4

代码实现:

package offer;

public class LongestCommonSubsequence {
public static void main(String[] args) {
LongestCommonSubsequence obj = new LongestCommonSubsequence();
String str1 = "caaac";
String str2 = "bbdaaaca";
System.out.println("LongestCommonSubsequence: " + obj.getMaxLength(str1, str2));
}
public int getMaxLength(String str1, String str2){
int m = str1.length();
int n = str2.length();
int resultArray[][] = new int[m + 1][n + 1];
int maxLength = 0;
//initialize the raw array
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++){
if(str1.charAt(i - 1) == str2.charAt(j - 1)
&& resultArray[i - 1][j - 1] != 0 )
resultArray[i][j] = 1 + resultArray[i - 1][j - 1];
else if(str1.charAt(i - 1) == str2.charAt(j - 1))
resultArray[i][j] = 1;
else
resultArray[i][j] = 0;
}
//output the resultArray
System.out.println("resultArray: ");
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
System.out.print(resultArray[i][j] + ", ");
}
System.out.println();
}

for(int i = 0; i <= m; i++)
for(int j = 0; j <= n; j++){
if(resultArray[i][j] > maxLength)
maxLength = resultArray[i][j];
}
return maxLength;
}
}


输出:




但是由于只要保留斜对角线的resultArray[i - 1][ j - 1] 所以没有必要声明整个二维数组 ,只要保留一个维度就可以了

, 最后遍历一下得到每一次生成行的最大值,下面就是按照这个思想实现的算法

代码2(只保留一维数组)

package offer;

public class LongestCommonSubsequence {
public static void main(String[] args) {
LongestCommonSubsequence obj = new LongestCommonSubsequence();
String str1 = "caaac";
String str2 = "bbdaaaca";
System.out.println("LongestCommonSubsequence: " + obj.getMaxLength(str1, str2));
}
public int getMaxLength(String str1, String str2){
int m = str1.length();
int n = str2.length();
//use tempArray to restore the data
int tempArray[] = new int
;
int maxLength = 0;
for(int i = 0; i < m; i++){
for(int j = n - 1; j >= 0; j--){
if(str1.charAt(i) != str2.charAt(j))
tempArray[j] = 0;
else{
tempArray[j] = tempArray[j - 1] + 1;
if(tempArray[j] > maxLength)
maxLength = tempArray[j];
}
}
if(str1.charAt(i) != str2.charAt(0)){
tempArray[0] = 0;
if(tempArray[0] > maxLength)
maxLength = tempArray[0];
}
/**
* output for test
****************************************/
for(int k = 0; k < n; k++)
System.out.print(tempArray[k] + ", ");
System.out.println();
/****************************************/

}
return maxLength;
}
}


输出:(循环单行输出)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐