You are given two strings, 'str1' and 'str2'. You have to find the length of the longest common substring.
A substring is a continuous segment of a string. For example, "bcd" is a substring of "abcd", while "acd" or "cda" are not.
Input: ‘str1’ = “abcjklp” , ‘str2’ = “acjkp”.
Output: 3
Explanation: The longest common substring between ‘str1’ and ‘str2’ is “cjk”, of length 3.
The First line of the test case contains the string ‘str1’.
The Second line contains the string ‘str2’.
Output format:
Return an integer representing the length of the longest common substring.
Note:
You don’t need to print anything. Just implement the given function.
wasdijkl
wsdjkl
3
The longest common substring is “jkl”, of length 3.
tyfg
cvbnuty
2
The longest common substring is “ty”, of length 2.
The expected time complexity is O(n*m),
Where ‘n’ and ‘m’ are the lengths of ‘st1’ and ‘str2’ respectively.
1 <= str1.length <= 1000
1 <= str2.length <= 1000
Can you think of using recursion for this problem of comparing the strings?
The basic idea is to recursively try and match characters from ‘str1’ to characters of ‘str2’ and vice versa also.
The steps are as follows:
O(2 ^ (n + m)), Where ‘n’ and ‘m’ is the length of ‘str1’ and ‘str2’, respectively.
We are using a recursive function to find the length of LCS where we are comparing each substring of the first string with the second string.
Hence the overall time complexity will be O(2 ^ (n + m)).
O(max(n , m)), Where ‘n’ and ‘m’ is the length of ‘str1’ and ‘str2’, respectively.
We are using a recursive function to find the length of LCS. In the worst case, the call stack may have max(n, m) states.
Hence the overall space complexity will be O(max(n, m)).