Given A string s and a Dictionary of words dict, determine if s can segmented into a spa Ce-separated 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".
Ideas
The first thing I did with that question was to match as much as possible, for example s = "ABCDEFABC" dict=["abc", "Def", and I just took out all the words in the dictionary in S, Finally, if s does not have any letters then it can break;
But the problem comes, s= "aaaaaaa" dict=["AAA", "AAAA", this time will be directly using AAA to divide s into Aaa,aaa,a, thus returning false.
For example, s= "ABCDEEFG" dict=["AB", "CDE", "ee", "CD", "FG", when used in the dictionary "CDE" to split, the result is AB, CDE, E, FG; Thus returning false.
"Dynamic Programming Problem solving"
"Key ★"
Starting with S[2]=c, we've found two dictionary words to match, namely: CDE,CD, we mark the lengths they can stitch together.
ab CDEEFG
AB
Cde
CD
---> Next, we'll start with the location of EFG or EEFG.
"Code"
1 Public classSolution {2 Public BooleanWordbreak (String s, set<string>dict) {3 Boolean[] t =New Boolean[S.length () +1];4T[0] =true;//set first to is true, why?5 //Because We need initial state6 7 for(inti=0; I<s.length (); i++){8 //should continue from match position9 if(!T[i])Ten Continue; One A for(String a:dict) { - intLen =a.length (); - intend = i +Len; the if(End >s.length ()) - Continue; - - if(T[end])Continue; + - if(S.substring (i, End). Equals (a)) { +T[end] =true; A } at } - } - - returnt[s.length ()]; - } -}
Leetcode--Word break dynamic planning, detailed understanding