A person who has never tasted all his wines will not experience the smell of water ~
Given a stringSAnd a dictionary of wordsDict, Determine ifSCan be 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"leet code"
.
[Solutions]
DP: ANS [I] indicates the subscript 0 ~ of S ~ Can I be represented by dict?
Ans [I] = the existence of K satisfies ans [k] & dict. Contains (S. substr (k + 1, I-k) = true.
1 bool Solution::wordBreak(std::string s, std::tr1::unordered_set<std::string> &dict) 2 { 3 if (s.length() == 0 || dict.size()==0) 4 { 5 return false; 6 } 7 int length = s.length(); 8 bool ans[length]; 9 for (int i = 0; i < length; i++)10 ans[i] = false;11 for (int i = 0; i < length; i++)12 {13 if (dict.find(s.substr(0, i+1)) != dict.end())14 ans[i] = true;15 for (int j = 0; j < i; j++)16 {17 if (ans[j]&&dict.find(s.substr(j+1, i-j))!=dict.end())18 {19 ans[i] = true;20 break;21 }22 }23 }24 return ans[length-1];25 }