1258. Synonymous Sentences
Input:
synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
text = "I am happy today but was sad yesterday"
Output:
["I am cheerful today but was sad yesterday",
"I am cheerful today but was sorrow yesterday",
"I am happy today but was sad yesterday",
"I am happy today but was sorrow yesterday",
"I am joy today but was sad yesterday",
"I am joy today but was sorrow yesterday"]// Find with path compression
string findRoot(unordered_map<string, string>& roots, const string& s) {
return roots[s] == s ? s : roots[s] = findRoot(roots, roots[s]);
}
void dfs(unordered_map<string, string>& roots, unordered_set<string>& words, int start, string& text, vector<string>& res) {
if (start >= text.length()) { // actually there is no equality case in this code
res.emplace_back(text);
return;
}
string cur; // current word
int idx;
for (idx = start; idx < text.length() && text[idx] != ' '; ++idx) {
cur += text[idx];
}
++idx; // skip whitespace
// Keep the current word unchanged
dfs(roots, words, idx, text, res);
string pre = text;
// Change the current word with its synonyms
if (roots.count(cur)) {
for (const string& word : words) {
if (cur != word && findRoot(roots, cur) == findRoot(roots, word)) {
text.replace(start, cur.length(), word);
dfs(roots, words, idx - cur.length() + word.length(), text, res);
text = pre; // reset to the previous state before replacement
}
}
}
}
// Union Find + DFS
vector<string> generateSentences(vector<vector<string>>& synonyms, string text) {
unordered_map<string, string> roots;
unordered_map<string, int> root_sz;
unordered_set<string> words;
// Union
for (const vector<string>& syn : synonyms) {
if (!roots.count(syn[0])) {
roots[syn[0]] = syn[0];
root_sz[syn[0]] = 1;
}
if (!roots.count(syn[1])) {
roots[syn[1]] = syn[1];
root_sz[syn[1]] = 1;
}
words.insert(syn[0]);
words.insert(syn[1]);
string r1 = findRoot(roots, syn[0]), r2 = findRoot(roots, syn[1]);
if (r1 != r2) {
if (root_sz[r1] >= root_sz[r2]) roots[r2] = r1;
else roots[r1] = r2;
}
}
vector<string> res;
// Backtracking
dfs(roots, words, 0, text, res);
// Sort lexicographically
sort(res.begin(), res.end());
return res;
}Last updated