Topic:
Given a non-empty string s and a dictionary worddict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Assume the dictionary does not contain duplicate words.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
test instructions and analysis: given a string and a dictionary, it is possible to use a dictionary word to divide a string. Using a deep traversal method, each time the string is judged to start with a word in the dictionary, and if it starts, the remaining string is judged, and if the last string length is 0, the words that can split the string are found. This saves the intermediate result with a hashmap, otherwise it will time out.
Code:
classSolution { PublicList<string> Wordbreak (String s, list<string>worddict) { returnDFS (S, Worddict,NewHashmap<string, linkedlist<string>>()); } List<String> DFS (String s,list<string> worddict,hashmap<string,linkedlist<string>>map) { if(Map.containskey (s))returnMap.get (s); LinkedList<String> res =NewLinkedlist<>(); if(s.length () = = 0) {Res.add (""); returnRes; } for(String word:worddict) {if(S.startswith (Word)) {List<String> sublist =DFS (s.substring (Word.length ()), worddict,map); for(String sub:sublist) {res.add (Word+ (Sub.isempty ()? "":" ")+sub); }}} map.put (S,res); returnRes; }}
[Leetcode] 140. Word Break II Java