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.
其一
DP
设状态为f(i),s[0,i]表示能否分词,
状态转移方程如下: f(i)=any_of(f(j)&&s[j+1,i]∈dict),0≤j
class Solution {
bool wordfind(string s, vector<string>& wordDict){
vector<string>::iterator it;
for(it=wordDict.begin();it!=wordDict.end();it++){
if(*it== s) return true;
}
return false;
}
bool indexfind(int s, vector<int>& wordDict){
vector<int>::iterator it;
for(it=wordDict.begin();it!=wordDict.end();it++){
if(*it== s) return true;
}
return false;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<int> visited;
queue<int> BFS;
BFS.push(0);
while(BFS.size()>0){
int start=BFS.front();
BFS.pop();
if(!indexfind(start,visited)){
visited.push_back(start);
for(int j=start;j<s.size();j++){
string str(s,start,j-start+1);
if(wordfind(str,wordDict)){
BFS.push(j+1);
if(j+1==s.size())
return true;
}
}
}
}
return false;
}
};
其二
BFS+DFS
用图来存储每个可以分词的位置,例如
s=”leetcode”
wordDict=[“le”,”leet”,”code”]
如下图所示,每个点表示每个可以分词的开始位置,每条边则是表示一个被分割的字符串,用BFS从字符串s创建出图,DFS寻找从开始位置到结束位置的一条路径,如果存在对应的路径则可以分词,对应则是寻找从0到9的一条路径,如果存在就代表可以分词。
class Solution {
bool wordfind(string s, vector<string>& wordDict){
vector<string>::iterator it;
for(it=wordDict.begin();it!=wordDict.end();it++){
if(*it== s) return true;
}
return false;
}
bool indexfind(int s, vector<int>& wordDict){
vector<int>::iterator it;
for(it=wordDict.begin();it!=wordDict.end();it++){
if(*it== s) return true;
}
return false;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<int> visited;
queue<int> BFS;
BFS.push(0);
while(BFS.size()>0){
int start=BFS.front();
BFS.pop();
if(!indexfind(start,visited)){
visited.push_back(start);
for(int j=start;j<s.size();j++){
string str(s,start,j-start+1);
if(wordfind(str,wordDict)){
BFS.push(j+1);
if(j+1==s.size())
return true;
}
}
}
}
return false;
}
};
参考:
http://www.acmerblog.com/leetcode-solution-word-break-6259.html
https://discuss.leetcode.com/topic/2545/a-solution-using-bfs/20