Question
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"
.
My Solusion
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
/* 动态规划解
初始化:
F(0, i): 表示substr[0,i)是否可分割
则:F(0, N) = ||_{i=1}^{i=N}{F(0, i) && F(i, N)}
边界条件:s为wordDict一个值
*/
if(wordDict.find(s) != wordDict.end())
return true;
int len = s.size();
vector<int> f(len, -1);
for(int i = 1; i < len; ++i){
string tmp = s.substr(0, i);
if(wordDict.find(tmp) != wordDict.end() && wordBreak(s, i, wordDict, f)) // F(0, i) && F(i, N)
return true;
}
return false;
}
bool wordBreak(string s, int beg, unordered_set<string>& wordDict, vector<int>& f)
{
if(f[beg] != -1)
{
return f[beg]; //加速
}
bool rst = false;
if(wordDict.find(s.substr(beg)) != wordDict.end()) // 边界条件
{
rst = true;
}else
{
for(int i = 1; i < s.size() - beg; ++i){
if(wordDict.find(s.substr(beg, i)) != wordDict.end() && wordBreak(s, beg + i, wordDict, f)) // F(beg, i) && F(i, N)
{
rst = true;
break;
}
}
}
f[beg] = rst;
return rst;
}
};