This is my function for determining the Longest Substring between two strings in Java.
public class Main {
public static String longestSubstring(String str1, String str2){
int row = str1.length();
int col = str2.length();
int[][] checker = new int[row][col];
int max = 0;
int r = 0;
int c = 0;
for(int i=0; i < row; i++){
for(int j=0; j < col; j++){
if(str1.charAt(i) == str2.charAt(j)){
if((i -1 > 0) && (j -1 >0)){
checker[i][j] = checker[i-1][j-1] +1;
}else{
checker[i][j]++;
}
max = checker[i][j];
r = i;
c = j;
}else continue;
}
}
StringBuilder sb = new StringBuilder();
while(true){
if(checker[r][c] == 0) break;
sb.append(str1.charAt(r));
r--;
c--;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
// write your code here
String str1 = "adedfrgyu";
String str2 = "arvbfrgykset";
String str3 = "aaaaaaatyuieo";
String str4 = "aaaaaklui";
System.out.println(longestSubstring(str1, str2));
}
}
The code compiles, but wondering is the algorithm is correct. It passes all the test cases that I could make up.
java
.) \$\endgroup\$ – greybeard Feb 15 '16 at 8:04