@@ -5,9 +5,11 @@ public class LCS3Strings {
5
5
public static void main (String [] args ) {
6
6
7
7
// String s1 = "abcgd", s2 = "bcgad", s3 = "ad"; // 2
8
- String s1 = "geeks" , s2 = "geeksfor" , s3 = "geeksforgeeks" ; // 5
9
- // String s1 = "abcausdhbvaauhdpqweasdgd", s2 = "qwaeohfdasasdfqpaew",
10
- // s3 = "bnprsdhfasoihqd"; // 2
8
+ String s1 = "abcd" , s2 = "agcfd" , s3 = "ad" ; // 2
9
+ // String s1 = "geeks", s2 = "geeksfor", s3 = "geeksforgeeks"; // 5
10
+ // String s1 = "abc", s2 = "agcfd", s3 = "aeg"; // 1
11
+ // String s1 = "abcausdhbvaauhdpqweasdgd", s2 = "qwaeohfdasasdfqpaew", s3 = "bnprsdhfasoihqd"; // 2
12
+ // String s1 = "abeti", s2 = "btje", s3 = "tjjabt";
11
13
12
14
System .out .println (lcs3StrRecursion (s1 , s2 , s3 , 0 , 0 , 0 ));
13
15
@@ -23,6 +25,8 @@ public static void main(String[] args) {
23
25
}
24
26
25
27
System .out .println (lcs3StrTopDownDP (s1 , s2 , s3 , 0 , 0 , 0 , storage ));
28
+ // bottom up
29
+ System .out .println (lcs3StrBottomUpDP (s1 , s2 , s3 ));
26
30
}
27
31
28
32
public static int lcs3StrRecursion (String s1 , String s2 , String s3 , int vidx1 , int vidx2 , int vidx3 ) {
@@ -77,4 +81,37 @@ public static int lcs3StrTopDownDP(String s1, String s2, String s3, int vidx1, i
77
81
78
82
return lcsLen ;
79
83
}
84
+
85
+ public static int lcs3StrBottomUpDP (String s1 , String s2 , String s3 ) {
86
+ int one = s1 .length (), two = s2 .length (), three = s3 .length ();
87
+ int [][][] storage = new int [one + 1 ][two + 1 ][three + 1 ];
88
+
89
+ for (int block = one - 1 ; block >= 0 ; block --) {
90
+
91
+ for (int row = two - 1 ; row >= 0 ; row --) {
92
+
93
+ for (int col = three - 1 ; col >= 0 ; col --) {
94
+
95
+ // logic from top down
96
+ char ch1 = s1 .charAt (block );
97
+ char ch2 = s2 .charAt (row );
98
+ char ch3 = s3 .charAt (col );
99
+
100
+ int lcsLen = 0 ;
101
+ if (ch1 == ch2 && ch2 == ch3 ) {
102
+ lcsLen = 1 + storage [block + 1 ][row + 1 ][col + 1 ];
103
+ } else {
104
+ int option1 = storage [block + 1 ][row ][col ];
105
+ int option2 = storage [block ][row + 1 ][col ];
106
+ int option3 = storage [block ][row ][col + 1 ];
107
+
108
+ lcsLen = Math .max (option1 , Math .max (option2 , option3 ));
109
+ }
110
+
111
+ storage [block ][row ][col ] = lcsLen ;
112
+ }
113
+ }
114
+ }
115
+ return storage [0 ][0 ][0 ];
116
+ }
80
117
}
0 commit comments