Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s ="leetcode"
,
dict =["leet", "code"]
.Return true because
"leetcode"
can be segmented as"leet code"
.UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
题目大意:给定字符串s与字典dict,判断字符串s能否由字典中的元素组成。
分析:使用动态规划法。dp[i]=true表示字符串中0到i-1部分的子字符串能由字典中字符串组成。
class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n=s.size(); vector<bool> dp(n+1, false); dp[0]=true; for(int i=1;i<=n;i++) { for(int j=i-1;j>=0;j--) { if(dp[j]) { string sub = s.substr(j,i-j); if(findWord(sub, wordDict)) { dp[i]=true; break; } } } } return dp[n]; } bool findWord(string s, vector<string>& wordDict) { for(int i=0;i<wordDict.size();i++) { if(s==wordDict[i]) return true; } return false; } };