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。下次做。