转自:http://blog.csdn.net/liushu1231/article/details/23393955
【题目】
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"
.
【解法】
看到这道题,第一反应就是深搜,暴力解法,代码如下:
- bool wordBreak(string s, unordered_set<string> &dict) {
- auto it = dict.find(s);
- if(it != dict.end()){
- return true;
- }
- for(int i = 0; i < s.length(); i++){
- string str1 = s.substr(0,i);
- string str2 = s.substr(i+1,s.length());
- if(wordBreak(str1,dict) && wordBreak(str2,dict))
- return true;
- }
- return false;
- }
- bool wordBreak(string s,unordered_set<string> &dict){
- vector<bool> f(s.length()+1,false);
- f[0] = true;
- for(int i = 1; i < s.length()+1 ;i ++){
- for (int j = i-1; j >= 0; j--){
- if(f[j] && (dict.find(s.substr(j,i-j))!=dict.end())){//注意substr的用法,substr(pos,len)
- f[i] = true;
- }
- }
- }
- return f[f.size()-1];
- }