|
| 1 | +package Dynamic_Programming.Longest_Common_SubString; |
| 2 | + |
| 3 | +// Problem Statement: Longest Common Substring |
| 4 | +// LeetCode Question: |
| 5 | + |
| 6 | +public class Problem_1_Longest_Common_Substring { |
| 7 | + // Brute Force Approach |
| 8 | + public int findLCSLength(String s1, String s2) { |
| 9 | + return findLCSLengthRecursive(s1, s2, 0, 0, 0); |
| 10 | + } |
| 11 | + |
| 12 | + private int findLCSLengthRecursive(String s1, String s2, int i1, int i2, int count) { |
| 13 | + if(i1 == s1.length() || i2 == s2.length()) |
| 14 | + return count; |
| 15 | + |
| 16 | + if(s1.charAt(i1) == s2.charAt(i2)) |
| 17 | + count = findLCSLengthRecursive(s1, s2, i1+1, i2+1, count+1); |
| 18 | + |
| 19 | + int c1 = findLCSLengthRecursive(s1, s2, i1, i2+1, 0); |
| 20 | + int c2 = findLCSLengthRecursive(s1, s2, i1+1, i2, 0); |
| 21 | + |
| 22 | + return Math.max(count, Math.max(c1, c2)); |
| 23 | + } |
| 24 | + |
| 25 | + // Top-down Dynamic Programming with Memoization Approach |
| 26 | + public int findLCSLength_1(String s1, String s2) { |
| 27 | + int maxLength = Math.min(s1.length(), s2.length()); |
| 28 | + Integer[][][] dp = new Integer[s1.length()][s2.length()][maxLength]; |
| 29 | + return findLCSLengthRecursive(dp, s1, s2, 0, 0, 0); |
| 30 | + } |
| 31 | + |
| 32 | + private int findLCSLengthRecursive(Integer[][][] dp, String s1, String s2, int i1, int i2, int count) { |
| 33 | + if(i1 == s1.length() || i2 == s2.length()) |
| 34 | + return count; |
| 35 | + |
| 36 | + if(dp[i1][i2][count] == null) { |
| 37 | + int c1 = count; |
| 38 | + if(s1.charAt(i1) == s2.charAt(i2)) |
| 39 | + c1 = findLCSLengthRecursive(dp, s1, s2, i1+1, i2+1, count+1); |
| 40 | + int c2 = findLCSLengthRecursive(dp, s1, s2, i1, i2+1, 0); |
| 41 | + int c3 = findLCSLengthRecursive(dp, s1, s2, i1+1, i2, 0); |
| 42 | + dp[i1][i2][count] = Math.max(c1, Math.max(c2, c3)); |
| 43 | + } |
| 44 | + |
| 45 | + return dp[i1][i2][count]; |
| 46 | + } |
| 47 | + |
| 48 | + // Bottom-up Dynamic Programming Approach |
| 49 | + public int findLCSLength_2(String s1, String s2) { |
| 50 | + int[][] dp = new int[2][s2.length()+1]; |
| 51 | + int maxLength = 0; |
| 52 | + for(int i=1; i <= s1.length(); i++) { |
| 53 | + for(int j=1; j <= s2.length(); j++) { |
| 54 | + dp[i%2][j] = 0; |
| 55 | + if(s1.charAt(i-1) == s2.charAt(j-1)) { |
| 56 | + dp[i%2][j] = 1 + dp[(i-1)%2][j-1]; |
| 57 | + maxLength = Math.max(maxLength, dp[i%2][j]); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return maxLength; |
| 62 | + } |
| 63 | +} |
0 commit comments