-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS.java
More file actions
46 lines (41 loc) · 1.36 KB
/
Copy pathLCS.java
File metadata and controls
46 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.List;
public class LCS {
static String lcs(String str1, String str2){
List<String> list1 = generateSubsequences(str1);
List<String> list2 = generateSubsequences(str2);
String lcs="";
for(String word1 : list1){
for(String word2 : list2){
if(word1.equals(word2) && word1.length() > lcs.length()){
lcs = word1;
}
}
}
return lcs;
}
static List<String> generateSubsequences(String str){
ArrayList<String> subseqList = new ArrayList<>();
int n = str.length();
for(int i=0;i<n;i++){
char firstChar = str.charAt(i);
if(subseqList.size() ==0){
subseqList.add("");
subseqList.add("" + firstChar);
continue;
}
int subLen = subseqList.size();
for(int j=0;j<subLen;j++){
String temp = subseqList.get(j) + firstChar;
subseqList.add(temp);
}
}
return subseqList;
}
public static void main(String[] args) {
String str1 ="ayc";
String str2 ="abc";
String ans = lcs(str1, str2);
System.out.println("LONGEST COMMON SUBSEQUENCE IS : "+ ans);
}
}