I know how to use dynamic programming to solve the problem of finding either the most longest common subsequence or longest common substring given two strings. However, I am having a hard time to come up a solution for the problem of finding the longest subsequence of string X which is a substring of string Y.
Here is my brute force solution:
- find all the subsequences of string X and sort them by length desc;
- iterate through the sorted subsequnces, if current subsequence is a substring of Y, return the subsequence.
It works but the running time could be bad. Suppose all characters in X are unique, then there are 2^m subsequnces, where m is the length of X. I think checking if a string is a substring of Y takes O(n), where n is length of Y. So the overall running time is O(n*2^m).
Is a better way to do this, possibly via DP?
Edit:
Here is an example what I want to solve:
Y: 'BACDBDCD'
X: 'ABCD'
The answer would be 'ACD', because 'ACD' is the longest subsequence of X which is also a substring of Y.