问题描述
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.
思路分析
给一个string和一组word,判断string是否是由这些word组成的。
动态规划的思想,判断i之前的j个字符组成的word是否在字典中出现,看最后一个字符位置是否是true即可。
代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
if(wordDict.size()==0) return false;
vector<bool> dp(s.size()+1,false);
dp[0]=true;
int prev = 0;
for(int i=1;i<=s.size();i++)
{
for(int j=i-1;j>=0;j--)
{
if(dp[j])
{
string word = s.substr(j,i-j);
if (std::find(wordDict.begin(), wordDict.end(), word) != wordDict.end())
{
dp[i]=true;
break; //next i
}
}
}
}
return dp[s.size()];
}
};
时间复杂度:
O(n2)
O
(
n
2
)
空间复杂度:
O(n)
O
(
n
)
反思
一开始好无头绪,后来又了一丢丢思路。