From 4c151c6777bd84330ab86d5e129b72513dd63f88 Mon Sep 17 00:00:00 2001 From: icoder211 <58630967+icoder211@users.noreply.github.com> Date: Fri, 13 Nov 2020 02:23:35 +0530 Subject: [PATCH] Added Longest Common substring of two strings Fixes #1718 --- .../LongestCommonSubstring.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 DynamicProgramming/LongestCommonSubstring.java diff --git a/DynamicProgramming/LongestCommonSubstring.java b/DynamicProgramming/LongestCommonSubstring.java new file mode 100644 index 000000000000..1efc2a494313 --- /dev/null +++ b/DynamicProgramming/LongestCommonSubstring.java @@ -0,0 +1,27 @@ +public class LongestCommonSubstring { + + public static String string1, string2; + public static int[][] dp; + public static void main(String[] args) { + int res = 0; + string1 = "abbaf"; + string2 = "abcdef"; + int n = string1.length(); + int m = string2.length(); + dp = new int[n+1][m+1]; + for(int i = 0;i <= n;i++) { + dp[0][i] = 0; + dp[i][0] = 0; + } + + for(int i = 1;i <= n;i++) { + for(int j = 1;j <= m;j++) { + if(string1.charAt(i-1) == string2.charAt(j-1)) { + dp[i][j] = 1 + dp[i-1][j-1]; + res = Math.max(res, dp[i][j]); + }else dp[i][j] = 0; + } + } + System.out.println(res); + } +}