题目:
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"
.
思路:
用NP的思路可以做,不过时间复杂度比较高。因此可以考虑使用动态规划DP的方式做。
代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
bool * dp = new bool[s.size()];
for(int i = 0; i<s.size(); i++)
{
dp[i] = isMatch(s.substr(0,i+1),dict);
if(dp[i])
{
continue;
}
else
{
for(int j=0;j<i;j++)
{
if(dp[j])
{
dp[i]|=isMatch(s.substr(j+1,i-j),dict);
}
}
}
}
return dp[s.size()-1];
}
bool isMatch(string str, unordered_set<string> &dict)
{
unordered_set<string>::const_iterator got = dict.find (str);
if(got != dict.end())
{
return true;
}
else
{
return false;
}
}
};
或者简洁一点
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
bool* dp = new bool[s.size() + 1];
for(int i = 0; i <= s.size(); i++){
dp[i] = false;
}
dp[0] = true;
for(int i = 1; i <= s.size(); i++){
for(int j = 0; j < i; j++){
dp[i] = dp[i] | (dp[j] && isWord(s.substr(j, i -j), dict));
}
}
return dp[s.size()];
}
bool isWord(string s, unordered_set<string> &dict){
unordered_set<string>::const_iterator itr = dict.find(s);
if(itr != dict.end()){
return true;
}
return false;
}
};