140 Word Break II
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
A solution is ["cats and dog", "cat sand dog"]
Algorithm (I am so close!):
First I find the intersection of the string and the dictionary words. We can do this with
std::string::find
. In this process, I also keep the location. I need to do this because I want to be able to preserve the order of the string itself.Now when I sort the string by its value pair (location), which is an NlogN operation, I preserve the original order of the string with the all the found words.
Next, I group all the words that are substrings of one another. However, I stop the first instance a substring isnt found. This just means that in the process of finding the words, we found an over lap between two words.
The next step would be to group words from the vector in a clever way that resembles possible sentences. I cannot simply pair
cat
andand
together, although they appear in different groups.
Last updated