Ex:- Longest common substring or subsequence between "concatenation" and "decatenation" is "catenation".
ex:- Between "ABABC" and "BABA" ==> "BAB"
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Scanner; public class LCS{ public static void main(String []args){ Scanner sc = new Scanner(System.in); System.out.println("Enter first string:"); String str1 = sc.next(); System.out.println("Enter second string:"); String str2 = sc.next(); System.out.print(longestCommonSubstring(str1, str2)); } public static String longestCommonSubstring(String str1, String str2){ for(int i=0; i<str1.length(); i++){ String temp = str1.substring(i); if(str2.contains(temp)) return temp; } return "Not Found"; } } |
Python
def longestCommonSubstring(str1, str2): for i in range(0,len(str1)): if str1[i:] in str2: return str1[i:] return "Not Found" str1 = input("Enter first string:") str2 = input("Enter second string:") print(longestCommonSubstring(str1, str2)) |