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"​​.

利用动态规划算法,创建一个vector记录0-i的字符串是否可以由字典中的词组成,若可以则继续判断剩下的是否可以由字典词组成。为防止s的一部分可以分割而另一部分不可分割,需全部遍历一遍s,而不能根据i跳跃遍历。



1 class Solution {
2 public:
3 bool wordBreak(string s, unordered_set<string>& wordDict) {
4 int n=s.length();
5 if(n<1) return true;
6 if(wordDict.empty()) return false;
7 vector<bool> dp(n+1,false);
8 dp[0]=true;
9 for(int i=0;i<n;i++)
10 {
11 if(dp[i])
12 {
13 for(int j=i;j<n;j++)
14 {
15 string tmps=s.substr(i,j-i+1);
16 if(wordDict.count(tmps))
17 dp[j+1]=true;
18 }
19 }
20 }
21 return dp[n];
22 }
23 };