Skip to content

Commit 82748d3

Browse files
committed
update: added optimal soln, bottom up DP to find LCS of 3 strings
1 parent 306bf44 commit 82748d3

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

β€ŽInterview Prep/section19_DynamicProgramming/LCS3Strings.java

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ public class LCS3Strings {
55
public static void main(String[] args) {
66

77
// 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";
1113

1214
System.out.println(lcs3StrRecursion(s1, s2, s3, 0, 0, 0));
1315

@@ -23,6 +25,8 @@ public static void main(String[] args) {
2325
}
2426

2527
System.out.println(lcs3StrTopDownDP(s1, s2, s3, 0, 0, 0, storage));
28+
// bottom up
29+
System.out.println(lcs3StrBottomUpDP(s1, s2, s3));
2630
}
2731

2832
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
7781

7882
return lcsLen;
7983
}
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+
}
80117
}

0 commit comments

Comments
Β (0)