Given A string s and a Dictionary of words dict, determine if s can segmented into a space-s Eparated sequence of one or more dictionary words.
for example, given
s = " Leetcode ",
dict = [" Leet "," code "] .
Return true because "leetcode" can be segmented as "leet code" .
A look at this topic, it feels inside backtracking, because this problem, in the backtracking method in the usual. On the code:
public Boolean wordbreak (String s, set<string> dict) { StringBuilder sb = new StringBuilder (); Return helper (S, dict, 0, SB); } Private Boolean helper (String s, set<string> dict, int index, StringBuilder sb) { if (index = = dict.size ()) {
return s.equals (sb.tostring ()); } Iterator<string> iter = Dict.iterator (); while (Iter.hasnext ()) { StringBuilder sb1 = new StringBuilder (SB); String dic = Iter.next (); Sb.append (DIC); Iter.remove (); if (helper (s, Dict, Index+1, SB)) return true; Dict.add (DIC); SB = SB1; } return false; }
Result timed out! In general, the time limit for backtracking is relatively wide, but timed out! There must be a space for optimization, pruning AH:,
public Boolean wordbreak (String s, set<string> dict) { StringBuilder sb = new StringBuilder (); Return helper (S, dict, 0, SB); } Private Boolean helper (String s, set<string> dict, int index, StringBuilder sb) { if (!s.startswith (sb.tostring ())) { return false; } if (index = = dict.size ()) { return s.equals (sb.tostring ()); } Iterator<string> iter = Dict.iterator (); while (Iter.hasnext ()) { StringBuilder sb1 = new StringBuilder (SB); String dic = Iter.next (); Sb.append (DIC); Iter.remove (); if (helper (s, Dict, Index+1, SB)) return true; Dict.add (DIC); SB = SB1; } return false; }
In fact, this pruning can subtract many branches, but still timeout! What to do? Only with the most efficient dynamic planning, on the code:
public Boolean WORDBREAK1 (String s, set<string> dict) { int length = S.length (); Boolean[] can = new boolean[length+1]; Can[0] = true; for (int i = 1, i <= length; i++) {for (int j = 0; J < i; J + +) { if (Can[j] && dict.contains (s.subs Tring (J, i))) { Can[i] = true; Break ; }}} return can[length]; }
A Boolean array of can[i] means that s.substring (0,i) is divisible, and the last element of the array is the one you are seeking.
Leetcode-word break