Longest Common Sequence between two strings
public class Solution {
public int longest(String source, String target) {
//edge case
if(source.length() == 0 || target.length() == 0) return 0;
int[][] M = new int[source.length()][target.length()];
// base case
M[0][0] = source.charAt(0) == target.charAt(0) ? 1 : 0;
for (int i = 1 ; i < source.length(); i++) {
M[i][0] = source.charAt(i) == target.charAt(0) ? 1 : M[i-1][0];
}
for (int j = 1 ; j < target.length(); j++) {
M[0][j] = source.charAt(0) == target.charAt(j) ? 1 : M[0][j-1];
}
//iterate row by row
for(int i = 1; i < source.length();i++){ //rows
for(int j = 1; j < target.length(); j++){ //columns
if(source.charAt(i) == target.charAt(j)){
M[i][j] = M[i-1][j-1] + 1;
} else {
M[i][j] = Math.max(M[i-1][j], M[i][j-1]);
}
}
}
return M[source.length() - 1][target.length() - 1];
}
}Last updated