[英]Longest Common Substring algorithm
i wrote a code which finds the LCS(longest common substring) of two strings. 我写了一个代码,找到两个字符串的LCS(最长公共子字符串)。 now i want to take it to the next level which means to find all the LCS combinations available and i'm not sure where to start.
现在,我想将其提升到一个新的水平,这意味着找到所有可用的LCS组合,但我不确定从哪里开始。 here's my code:
这是我的代码:
package MyPackage;
public class LCSAlgo {
//finds the first col and first row of the matrix
public static int[] [] LCSBase2(String a , String b){
int [][] arr = new int[a.length()][b.length()];
boolean flaga = false;
boolean flagb = false;
for(int i = 0 ; i<a.length();i++){
if(a.charAt(i) == b.charAt(0) || flaga){
flaga=true;
arr[i][0] = 1;
}
else{
arr[i][0] = 0;
}
}
for(int j = 0 ; j<b.length();j++){
if(b.charAt(j) == a.charAt(0) || flagb){
flagb=true;
arr[0][j] = 1;
}
else{
arr[0][j] = 0;
}
}
return arr;
}
//Fill the matrix with the substring combination
public static int [][] LCSSol( String a , String b){
int [][] arr2 = LCSBase2(a,b);
for(int i = 1 ; i<a.length(); i++){
for(int j = 1 ; j<b.length();j++){
if(a.charAt(i) == b.charAt(j)){
arr2[i][j] = arr2[i-1][j-1]+1;
}
else{
if(arr2[i][j-1]>arr2[i-1][j]){
arr2[i][j] = arr2[i][j-1];
}
else
arr2[i][j] = arr2[i-1][j];
}
}
}
return arr2;
}
//prints the matrix
public static void Print2D(int i , int j , int [][]arr){
for(int a = 0;a<i;a++){
System.out.println();
for(int b = 0; b<j ; b++){
System.out.print(arr[a][b]);
}
}
}
//returns one common substring of two Strings.
public static String CommonSubstring( String a,String b ){
int [] [] arr = LCSSol(a, b);
int i = a.length()-1;
int j = b.length()-1;
String sub = "",subrev="";
while(i>=0 && j>=0 && arr[i][j]>0){
if(a.charAt(i) == b.charAt(j)){
sub+=a.charAt(i);
i--;
j--;
}
else{
if(arr[i][j-1]>arr[i-1][j]){
j--;
}
else{
i--;
}
}
}
for( i=sub.length()-1;i>=0;i--){
subrev+=sub.charAt(i);
}
return subrev;
}
public static void main(String [] args){
String s1 = "abcbdab";
String s2 = "bdcaba";
System.out.println(CommonSubstring(s1, s2));
}
}
could someone guide me how to find all the combinations? 有人可以指导我如何找到所有组合吗?
You could use an external library like Commons-collections . 您可以使用Commons-collections之类的外部库。 Once this library is inside your classpath you can permute all combinations easily with CollectionsUtils :
一旦该库位于您的类路径中,就可以使用CollectionsUtils轻松置换所有组合:
CollectionUtils.permutations(collection)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.