-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0140.WordBreakII.cpp
More file actions
61 lines (50 loc) · 1.53 KB
/
0140.WordBreakII.cpp
File metadata and controls
61 lines (50 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
unordered_set<string> m_dict;
string* m_string;
int m_n;
vector<string> m_workingWords, m_brokenStrings;
void breakWords(const int index, const int count) {
if (index + count > m_n) {
// Index can only be more than n for end of string.
if (index < m_n) return;
// Add string to list.
const int brokenIndex = m_brokenStrings.size();
m_brokenStrings.emplace_back("");
// Convert working set into string directly.
const int wordsEnd = m_workingWords.size();
const int spaceEnd = wordsEnd - 1;
for (int i = 0; i < wordsEnd; i++) {
// Add word + space.
m_brokenStrings[brokenIndex] += m_workingWords[i] + " ";
}
// Remove trailing space.
m_brokenStrings[brokenIndex].pop_back();
return;
}
// Check for longer variations on the same word.
breakWords(index, count + 1);
// Check if word exists in dictionary.
const string word = m_string->substr(index, count);
if (m_dict.find(word) == m_dict.end()) return;
// Add word to working set.
m_workingWords.push_back(word);
// Check for words after.
breakWords(index + count, 1);
// Remove word from working set.
m_workingWords.pop_back();
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Setup calculation variables.
m_dict = unordered_set<string>(wordDict.begin(), wordDict.end());
m_string = &s;
m_n = m_string->size();
// Break words.
breakWords(0, 1);
return m_brokenStrings;
}
};