Given A string s and a Dictionary of words dict, add spaces in s to construct a sentence where Each of the word is a valid dictionary word.
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"] .
Problem Solving Ideas:
Refer to the method of thinking two of the solution, modify the code, let it show the path, Java implementation is as follows:
static public list<string> Wordbreak (String s, set<string> worddict) {list<string> List = new ArrayList <String> ();d FS (list, S, Worddict, New Hashset<string> (), New arraylist<string> ()); return list;} Static public boolean DFS (list<string> List, String S, set<string> dict,set<string> Unmatch, list< String> alist) {boolean ismatch=false;for (String prefix:dict) {if (s.equals (prefix)) {alist.add (prefix)}; StringBuilder sb = new StringBuilder (); for (String str:alist) {sb.append (str); Sb.append ("");} List.add (sb.substring (0, Sb.length ()-1)); Alist.remove (Alist.size ()-1); ismatch=true;continue;} else if (s.startswith (prefix)) {String suffix = s.substring (prefix.length ()); if (!unmatch.contains (suffix)) {Alist.add (prefix), if (!dfs (list, suffix, dict, Unmatch, alist)) unmatch.add (suffix); else Ismatch=true;alist.remove (Alist.size ( )-1);}}} return isMatch;}
Java for Leetcode-Word break II