forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1258-SynonymousSentences.cs
67 lines (58 loc) · 2.09 KB
/
1258-SynonymousSentences.cs
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
62
63
64
65
66
67
//-----------------------------------------------------------------------------
// Runtime: 284ms
// Memory Usage: 31.4 MB
// Link: https://leetcode.com/submissions/detail/368578305/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _1258_SynonymousSentences
{
public IList<string> GenerateSentences(IList<IList<string>> synonyms, string text)
{
var result = new List<string>();
if (synonyms == null || synonyms.Count == 0) return result;
var map = new Dictionary<string, SortedSet<string>>();
foreach (var wordPair in synonyms)
{
SortedSet<string> set;
if (map.ContainsKey(wordPair[0]))
set = map[wordPair[0]];
else
set = new SortedSet<string>(StringComparer.Ordinal);
set.Add(wordPair[0]);
set.Add(wordPair[1]);
map[wordPair[0]] = set;
map[wordPair[1]] = set;
}
var words = text.Split();
foreach (var word in words)
{
if (!map.ContainsKey(word))
{
var set = new SortedSet<string>();
set.Add(word);
map[word] = set;
}
}
var builders = new List<string>();
DFS(words, 0, map, builders, result);
return result;
}
private void DFS(string[] words, int index, Dictionary<string, SortedSet<string>> map, List<string> builders, List<string> result)
{
if (index == words.Length)
{
result.Add(string.Join(" ", builders));
return;
}
foreach (var replacement in map[words[index]])
{
builders.Add(replacement);
DFS(words, index + 1, map, builders, result);
builders.RemoveAt(builders.Count - 1);
}
}
}
}