问题描述
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”.
思考: 如何找到最后解
想法:图算法,BFS和DFS,遍历到最后节点/用动态规划
- 1、节点:(x)表示从0-X有word,即前缀长度
- 2、边,表示从(x)到(y)可以加一个word到达;
- 3、动态规划 dp[i] 表示0-i序列已经在字典找到,那么可以根据dp[i]更新dp[i + k],
代码
DFS
class Solution {
public:
bool help(string &s, int now, unordered_set<string> &d, vector<bool> &visited){
if(now >= s.length())
return true;
if(visited[now])
return false;
visited[now] = true;
for(int i = now; i < s.length(); i++)
if(d.find(s.substr(now, i - now + 1)) != d.end() && help(s,i + 1, d,visited))
return true;
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> visited(s.length(),false);
return help(s,0,wordDict,visited);
}
};
BFS
class Solution {
public:
bool help(string &s,unordered_set<string> &d, vector<bool> &visited){
if(s.length() == 0)
return true;
queue<int> q;
visited[0] = true;
for(q.push(0); !q.empty(); q.pop()){
int ind = q.front();
for(int i = ind; i < s.size(); i++)
if(d.find(s.substr(ind, i - ind + 1)) != d.end()){
if(i + 1 >= s.length())
return true;
if(!visited[i + 1]){
q.push(i + 1);
visited[i + 1] = true;
}
}
}
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> visited(s.length(),false);
return help(s,wordDict,visited);
}
};
动态规划
class Solution {
public:
bool help(string &s,unordered_set<string> &d, vector<bool> &dp){
if(s.length() == 0)
return true;
dp[0] = true;
for(int ind = 0; ind < s.size(); ind++){
if(!dp[ind])
continue;
for(int i = ind; i < s.size(); i++)
if(d.find(s.substr(ind, i - ind + 1)) != d.end()){
if(i + 1 >= s.length())
return true;
dp[i + 1] = true;
}
}
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
vector<bool> visited(s.length(),false);
return help(s,wordDict,visited);
}
};