I saw this code implementation here. It basically takes two strings, finds the longest common substring, and returns the length of it. I wanted to modify it slightly to get the starting indexes of the substrings for each words, but just can't figure out. I know it should be possible, since we are working with indexes of the string. I will write my edited version of the code below:
public class Main {
public class Answer {
int i, j, len;
Answer(int i, int j, int len) {
this.i = i;
this.j = j;
this.len = len;
}
}
public Answer find(String s1,String s2){
int n = s1.length();
int m = s2.length();
Answer ans = new Answer(0, 0, 0);
int[] a = new int[m];
int b[] = new int[m];
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
if(s1.charAt(i)==s2.charAt(j)){
if(i==0 || j==0 )a[j] = 1;
else{
a[j] = b[j-1] + 1;
}
ans.len = Math.max(ans.len, a[j]);
ans.i = i;
ans.j = j;
}
}
int[] c = a;
a = b;
b = c;
}
return ans;
}
}