LeetCode-Word Break
Given a stringSAnd a dictionary of wordsDict, Determine ifSCan 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"leet code".
In this example, we mainly want to see whether the words in a sentence string can be divided into words in the dictionary.
If flag [j] is true, a variable k must exist, which can satisfy the condition that flag [k] is true, and substr (k, j-k) is in the dictionary.
However, in this example, we do not care about the final division method.
Class Solution {public: bool wordBreak (string s, unordered_set
& Dict) {int length = s. size (); vector
Val (length + 1, false); val [0] = true; // <set int I = 0 according to the length; int j = 0; for (I = 0; I <length; I ++) {if (val [I]) // <the previous length can be decomposed {for (j = 1; (I + j) <= length; j ++) {string tmp = s. substr (I, j); if (dict. count (tmp)> 0) {val [I + j] = true ;}}} return val [length] ;}};
There is a second example:
Word Break II
Given a stringSAnd a dictionary of wordsDict, Add spaces inSTo construct a sentence where each word is a valid dictionary word.
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"].
In this example, we need to put the decomposition result in a vector struct.
One method is the DFS method, which has not been studied yet.
The method in the first example is used as a reference here to check whether the partition can be made. If the partition can be made, it is then stored through traversal.
class Solution {public: void breakWord(vector
&res, string &s, unordered_set
&dict, string str, int idx, vector
&dp) { string substr; for (int len = 1; idx + len <= s.length(); ++len) { if (dp[idx + len] && dict.count(s.substr(idx,len)) > 0) { substr = s.substr(idx, len); if (idx + len < s.length()) { breakWord(res, s, dict, str + substr + " ", idx + len, dp); } else { res.push_back(str + substr); return; } } } } vector
wordBreak(string s, unordered_set
&dict) { vector
dp(s.length() + 1, false); dp[0] = true; for (int i = 0; i < s.length(); ++i) { if (dp[i]) { for (int len = 1; i + len <= s.length(); ++len) { if (dict.count(s.substr(i, len)) > 0) { dp[i + len] = true; } } } } vector
res; if (dp[s.length()]) breakWord(res, s, dict, "", 0, dp); return res; }};