您的位置:首页 > 其它

每天一道LeetCode-----将字符串切分成若干单词,使得每个单词都在给定的字典中,求出所有的切分结果

2018-01-29 14:42 525 查看

Word Break

原题链接Word Break



给定一个字符串和单词字典,将字符串切分成若干个单词,使每个单词都在字典中。判断是否可以成功切分

假设字符串s[0 : n-1]可以成功切分成若干个单词,那么一定存在一个i使得s[0 : i-1]可以成功切分成若干个单词,同时s[i : n-1]在字典中存在,可以采用动态规划的思想求解

令dp[i]表示s[0 : i-1]是否可以成功切分成若干单词组合,最终要求解的是dp


那么每求一个dp[i]使,就在i前面寻找是否存在一个j使得dp[j]为真且s[j : i-1]在字典中

代码如下

class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> hash;
size_t maxLen = 0;
for(auto& word : wordDict)
{
hash.insert(word);
maxLen = std::max(maxLen, word.size());
}
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for(int i = 1; i <= s.size(); ++i)
{
for(int j = i - 1; j >= 0 && (i - j) <= maxLen; --j)
{
/* 寻找一个j使得s[0 : j-1]可以拆分 */
if(dp[j])
{
/* 判断s[j : i-1]是否在字典中 */
string word = s.substr(j, i - j);
if(hash.find(word) != hash.end())
{
/* 标记s[0 : i-1]可以成功拆分 */
dp[i] = 1;
break;
}
}
}
}
return dp[s.size()];
}
};


Word Break II

原题链接Word Break II



寻找所有的拆分结果

还是采用上述的思路,要将s[0 : n-1]拆分,那么就从后向前寻找i使得s[i : n-1]在字典中,然后拆分s[0 : i-1],将结果进行组合

代码如下

class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> hash;
for(auto& word : wordDict)
hash.insert(word);
return breakWord(s, hash);
}
private:
vector<string> breakWord(string& s, unordered_set<string>& hash)
{
/* 防止重复计算 */
if(m.find(s) != m.end())
return m[s];
vector<string> res;
for(int i = s.size() - 1; i >= 0; --i)
{
string word = s.substr(i);
if(hash.find(word) != hash.end())
{
string str = s.substr(0, i);
vector<string> prevWords = breakWord(str, hash);
for(auto& words : prevWords)
res.emplace_back(words + " " + word);
if(i == 0)
res.emplace_back(word);
}
}
m[s] = res;
return res;
}
private:
unordered_map<string, vector<string>> m;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode
相关文章推荐