LeetCode:Word Break II
2014-09-11 09:45
357 查看
Return all such possible sentences.
For example, given
s =
"catsanddog",
dict =
["cat", "cats", "and", "sand", "dog"].
A solution is
["cats and dog", "cat sand dog"].
class Solution { public: vector<string> myString; vector<string> wordBreak(string s, unordered_set<string> &dict) { <span style="white-space:pre"> </span>vector<string> result; result.clear(); if(s.empty()||dict.empty()) return result; bool* dp = new bool[s.size() + 1]; map<int,vector<int>> index; memset(dp,false,s.size() + 1); dp[0] = true; for(int i=1;i<s.size()+1;i++) { <span style="white-space:pre"> </span>for(int j=0;j<i;j++) { if(dp[j]) { string str = s.substr(j,i-j); dp[i] = (dict.find(str) != dict.end())?true:false | dp[i]; if(dict.find(str) != dict.end()) { map<int,vector<int>>::iterator it = index.find(i); if(it!=index.end()) it->second.push_back(j); else { vector<int> temp; temp.push_back(j); index.insert(make_pair(i,temp)); } continue; } } } } if(!dp[s.size()]) return result; else report(s,index,result,s.size()); return result; } void report(string &s,map<int,vector<int>>& index, vector<string>& result,int n) { if(n == 0) { string str; for(int i = myString.size()-1;i>=0;i--) { str+=myString[i]; if(i!=0) str.push_back(' '); } result.push_back(str); } else { map<int,vector<int>>::iterator it = index.find(n); if(it!=index.end()) { for(int i = 0; i<it->second.size();i++) { myString.push_back(s.substr(it->second[i],n - it->second[i])); report(s,index,result,it->second[i]); myString.pop_back(); } } } } };继word break,首先用word break的方法判断是否可以匹配,然后利用保存的路径返回结果。
路径的保存用到了map,map的索引为字符串的字符对应的下标,索引对应的值为一个数组,该数组保存着以该索引为末尾字符的在dict中的匹配串的开始字符对应的下标。
例:
s = "abcd"
dict = ["a","b","abc","cd"]
map最终为
[
1->{0}
2->{1}
3->{0}
4->{2}
]
这样,当输出结果时,以尾字符开始递归查询,具体如下:
map.find(4)->second[0]=2 <-----------------> s.substr(2,4-2) = "cd"
map.find(2)->second[0]=1 <-----------------> s.substr(1,2-1) = "b"
map.find(1)->second[0]=0 <-----------------> s.substr(0,1-0) = "a"
将“a”、“b”、“cd”组合即可已AC 52ms
相关文章推荐
- [leetcode]break word II
- Word Break II (leetcode)
- leetcode 140: Word Break II
- [leetcode] Word Break II
- 【leetcode】Word Break II
- [LeetCode] WordBreak II, Solution
- 【leetcode】Word Break II (hard)★
- [Leetcode] Word Break II
- leetcode之Word Break II
- [LeetCode]Word Break II
- Leetcode: Word Break II
- 【LeetCode】Word Break && Word Break II
- LeetCode 140. Word Break II
- Leetcode---word Break II
- [LeetCode]题解(python):140-Word Break II
- LeetCode - Word Break II
- leetcode 140:Word Break II 采用很巧妙的动态规划和DFS联合使用 JAVA源代码实现
- LeetCode-Word Break II
- leetcode — word-break-ii
- LeetCode 140 Word Break II--In C++