Given a string s and a dictionary of words Dict, determine if s can segmented into a space-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".
Remember the first time to do the dynamic planning of the problem was opened this problem, but there is no idea. Now the dynamic planning of the problem brush a lot, and today to do this problem quickly came up with the state and state transfer equation, can not but say a little progress.
Define A[I] to indicate whether the sub-characters 0 to subscript I can be split into multiple words in Dict.
Then A[i] and a[j],0<=j< I all have relations, namely A[i] and former a[] in the former i-1 items are related, specifically:
- If a[0] is 1, determine if the characters in the middle of the index from 1 to I end of the character in Dict, if in, set A[i] is 1, jump out, otherwise enter the second step;
- If A[1] is 1, determine if the characters in the middle of the index from 2 to I end of the character in Dict, if in, set A[i] is 1, jump out, otherwise enter the second step;
.....
This keeps traversing to the a[i-1] position.
In the above traversal if traversing to a step j,a[j]=1 and j+1 to I represent the string appears in the Dict, indicating that the first J string can be divided into dict words, j+1 to I string strings can also be divided into dict words, This means that the first I word RP is divided into dict words.
When actually writing the code, J can start the traversal backwards from I, which reduces the number of traversal times.
Runtime:4ms
classSolution { Public:BOOLWordbreak (stringS unordered_set<string>& Worddict) {intLength=s.size ();int*a=New int[Length] (); for(intI=0; i<length;i++) { for(intj=i;j>=0; j--) {if(j==i) {A[i]=isexist (s),0, i,worddict); }Else if(a[j]==1) {A[i]=isexist (s,j+1, i,worddict); }if(a[i]==1) Break; } }returna[length-1]==1; }intIsexist (string&s,intFirstintLast unordered_set<string>&worddict) {stringStr=s.substr (first,last-first+1);if(Worddict.count (str))return 1;Else return 0; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode139:word break