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"
.
Solution1:DP
申请bool类型的存储空间 bool *res=new bool[s.size()+1];
res[i]=true表示字符串s的前i位在字典中
res[i]=false表示字符串s的前i位不在字典中
res[s.size()]的值就是返回值
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
bool res[s.size()+1];
for(int i=0;i<s.size()+1;i++)
res[i]=false;
res[0]=true;
if(s.size()<=0)
return true;
else if(dict.size()<=0)
return false;
for(int i=1;i<=s.size();i++)
{
for(int j=0;j<i;j++)
{
if(res[j]&&(dict.count(s.substr(j,i-j))>0))
{
res[i]=true;
break;
}
}
}
return res[s.size()];
}
};
Solution2 from https://oj.leetcode.com/discuss/8479/a-solution-using-bfs
思想:一个队列存储需要访问的位,一个set集判断该位是否访问过
对任一个字符串s(s[0]~s[n-1]),先将0压入队列,然后判断s.substr(0,i+1)是否存在字典中,存在则将i+1压入队列中,表示s的子串前i位在字典中,剩下的就是判断i+1至s.size()-1位是否在字典中,在则return true
bool wordBreak(string s, unordered_set<string> &dict) {
// BFS
queue<int> BFS;
unordered_set<int> visited;
BFS.push(0);
while(BFS.size() > 0)
{
int start = BFS.front();
BFS.pop();
if(visited.find(start) == visited.end())
{
visited.insert(start);
for(int j=start; j<s.size(); j++)
{
string word(s, start, j-start+1);
if(dict.find(word) != dict.end())
{
BFS.push(j+1);
if(j+1 == s.size())
return true;
}
}
}
}
return false;
}