Description:
Given a string s and a dictionary of words dict, determine if s can 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 as "leet code"
.
Code:
1 bool wordBreak(string s, unordered_set<string>& wordDict) { 2 //flag[i][j]表示s[i]...s[j]是否为一个word 3 int length = s.size(); 4 bool flag[MAX][MAX]={false}; 5 for (int i = 0; i < length; ++i) 6 { 7 string str(s,i,1); 8 if (wordDict.find(str)!=wordDict.end()) 9 flag[i][i] = true; 10 } 11 12 for (int r=2; r<=length; ++r) 13 {//计算长度为2,3,...n的字符串 14 for (int i=0; i <= length-r; ++i) 15 { 16 int j = i+r-1;//j<=length-1 17 //计算flag[i][j]; 18 string str(s,i,r); 19 if (wordDict.find(str)!=wordDict.end()) 20 { 21 flag[i][j] = true; 22 continue; 23 } 24 for (int k = i; k < j; ++k) 25 { 26 if (flag[i][k]&&flag[k+1][j]) 27 { 28 flag[i][j] = true; 29 break; 30 } 31 } 32 } 33 } 34 return flag[0][length-1]; 35 }