Problem statement task: Given
two string sequences, write an algorithm to find the length of longest subsequence
present in both of them.
These kind of dynamic programming questions are very famous
in the interviews like Amazon, Microsoft, Oracle and many more.
What is Longest Common Subsequence: A
longest subsequence is a sequence that appears in the same relative order,
but not necessarily contiguous(not substring) in both the string.
Example:
Java Implementation using multiple loop
public class LCSNaive {
public static void main(String[] args) {
String
str1 = "ACBDEA";
String
str2 = "ABCDA";
String
result = lcs(str1, str2);
System.out.println(result);
}
static String lcs(String str1, String str2)
{
int len1 = str1.length();
int len2 = str2.length();
int j = 0, ji = 0;
String
result = "";
for (int i = 0; i < len1; i++) {
for (; j < len2; j++) {
if (str1.charAt(i) == str2.charAt(j)) {
result
+= str1.charAt(i);
ji
= j;
break;
}
}
if (j == len2)
j
= ji + 1;
}
return result;
}
}
Output:
ACDA

No comments:
Post a Comment