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"
.
本題如果暴力的話,超時
本題用動規
設dp[i]表示s[0,i)之間存在劃分使分隔後的字串都在dict裡面
則
dp[i]=
true, 如果s[0,i)在dict裡面
true,如果dp[k]=true (即s[0,k)存在劃分在dict裡面)且s[k,i)在dict裡面
false,其他(預設)
注意程式是前閉後開
bool wordBreak(string s, unordered_set<string> &dict){ int n = s.length(); vector<bool> dp(n+1,false); dp[0]=true; for(int i = 1 ; i < n+1; ++ i){ for(int j = 0 ; j < i; ++ j){ if(dp[j]&&dict.find(s.substr(j,i-j))!=dict.end()){ dp[i] = true; break; } } } return dp[n]; }