Giving a string and an string dictionary, find the longest string in dictionary which can formed by deleting some characters of the giving string.
Example:
S = abpcplea,
Dict = {ale, apple, monkey, plea},
the return "apple"
Can somebody provide trie solution( O(N*K) ), N: length of string, K: length of longest word?
This can be solved using DP.
The state is: (node, ind), representing the current trie node, and the current index in the given word, respectively.
The transitions are:
Of course, the base case is when you reach a leaf or the end of the string.
I think at least we have to check all words in dictionary, so if L = length of dictionary, we can solve in O(N * L).
You can check if one string is other's substring in O(N) (see here), so check all words in dictionary and return longest one.