Given two string X and Y. The task is to find the length of longest subsequence of string X which is substring in sequence Y.
Input : X = "ABCD", Y = "BACDBDCD" Output : 3 "ACD" is longest subsequence of X which is substring of Y. Input : X = "A", Y = "A" Output : 1
Method 1 (Brute Force):
Use brute force to find all the subsequence of X and for each subsequence check whether it is substring of Y or not. If it is substring of Y, maintain a maximum length varible and compare length with it.
Method 2: (Dynamic Programming):
Let n be length of X and m be length of Y. Create a 2D array ‘dp’ of m + 1 rows and n + 1 columns. Value dp[i][j] is maximum length of subsequence of X[0….j] which is substring of Y[0….i]. Now for each cell of dp fill value as :
for (i = 1 to m) for (j = 1 to n) if (x[i-1] == y[j - 1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = dp[i][j-1];
And finally, the length of the longest subsequence of x which is substring of y is max(dp[i][n]) where 1 <= i <= m.
Below is implementation this approach:
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find longest bitonic sequence such that increasing and decreasing parts are from two different arrays
- Ways of transforming one string to other by removing 0 or more characters
- Quick way to check if all the characters of a string are same
- Print the string after the specified character has occurred given no. of times
- Find the character in first string that is present at minimum index in second string
- Lexicographically n-th permutation of a string
- Non-decreasing subsequence of size k with minimum sum
- Paper Cut into Minimum Number of Squares | Set 2
- Find maximum possible stolen value from houses
- Count binary strings with k times appearing adjacent two set bits
- Find number of times a string occurs as a subsequence in given string
- Given two strings, find if first string is a subsequence of second
- Printing Longest Common Subsequence
- Longest Common Substring | DP-29
- Longest Common Subsequence | DP-4
Improved By : nitin mittal