683 · Word Break III
Algorithms
Medium
Description
Give a dictionary of words and a sentence with all whitespace removed, return the number of sentences you can form by inserting whitespaces to the sentence so that each word can be found in the dictionary.
Ignore case
Example
Example1
Input:
“CatMat”
[“Cat”, “Mat”, “Ca”, “tM”, “at”, “C”, “Dog”, “og”, “Do”]
Output: 3
Explanation:
we can form 3 sentences, as follows:
“CatMat” = “Cat” + “Mat”
“CatMat” = “Ca” + “tM” + “at”
“CatMat” = “C” + “at” + “Mat”
Example1
Input:
“a”
[]
Output:
0
解法1:DP。
注意transform可以将字符串全变成大/小写。注意::tolower的用法,不是std::tolower,因为它定义在全局作用域上。
class Solution {
public:
/**
* @param s: A string
* @param dict: A set of word
* @return: the number of possible sentences.
*/
int wordBreak3(string &s, unordered_set<string> &dict) {
int n = s.size();
transform(s.begin(), s.end(), s.begin(), ::tolower);
unordered_set<string> dict2;
for (auto it = dict.begin(); it != dict.end(); ++it) {
string str = *it;
transform(str.begin(), str.end(), str.begin(), ::tolower);
dict2.insert(str);
}
vector<int> dp(n + 1, 0); //dp[i] is the # of sentences with s[0..i-1]
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
if (dict2.find(s.substr(i - 1, j - i + 1)) != dict2.end()) {
dp[j] += dp[i - 1];
}
}
}
return dp[n];
}
};
解法2:DFS。下次做。
这篇博客探讨了如何解决WordBreak III问题,即给定一个字符串和一个字典,找出能由字典中单词组成的句子数量。作者提供了两种解法:动态规划(DP)和深度优先搜索(DFS)。在DP方法中,通过创建一个动态数组来记录到当前位置能组成的句子数。在DFS方法中,计划使用递归策略遍历所有可能的分割。博客还强调了在处理字符串时要注意大小写转换,并给出了详细的代码实现。

被折叠的 条评论
为什么被折叠?



