I have made the following Java code for searching for the longest substring that is common between a pair of strings. The code is as follows:
public static void main(String[] args) {
// TODO code application logic here
String cad1="xyzdistancerttp";
String cad2="abcxtwndistattttt";
String seq, lcs;
seq="";
lcs="";
System.out.println(cad1.length());
for (int i=0;i<cad1.length();i++){
for (int j=0;j<cad2.length();j++){
if (cad1.charAt(i)==cad2.charAt(j)){
seq=seq+cad1.charAt(i);
i++;
}
else{
if (seq.length()>lcs.length()){
lcs=seq;
seq="";
}
}
}
}
System.out.println(lcs);
}
When I test it with those strings the program returns the string dist that is correct, but when I change the strings to:
String cad1="xyzdistancerttt";
String cad2="abcxtwndistattttt";
I got an index out of bounds exception. Also with the following change:
String cad1="xyzdistancertttttp";
String cad2="abcxtwndistatttttsss";
I have as a result the string cttttt, but it should only print ttttt. Any help?
Thanks