[Geeks for Geeks] Word Break - Part 2

Word Break - Part 2

Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.

Follow examples for better understanding.

  • Time : O(s^2)
  • Space : O(dict)
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
struct Trie{
Trie* next[26];
bool eof = false;
Trie() {
memset(next, 0, sizeof(next));
}
void insert(string& s, int pos = 0) {
if(pos == s.length()) eof = true;
else {
if(!next[s[pos]-'a']) next[s[pos]-'a'] = new Trie();
next[s[pos]-'a']->insert(s, pos + 1);
}
}
void query(Trie* root, string& s, string& build, vector<string>& res, int pos = 0) {
if(pos == s.length()) {
if(eof) res.push_back(build);
} else {
if(eof) {
build.push_back(' ');
root->query(root, s, build, res, pos);
build.pop_back();
}
if(!next[s[pos]-'a']) return;
build.push_back(s[pos]);
next[s[pos]-'a']->query(root, s, build, res, pos + 1);
build.pop_back();
}
}
};
class Solution{
public:
vector<string> wordBreak(int n, vector<string>& dict, string s)
{
Trie* trie = new Trie();
for(auto& dic : dict)
trie->insert(dic);
vector<string> res;
trie->query(trie, s, string() = "", res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/word-break-part-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.