cs: add «1233. Remove Sub-Folders from the Filesystem»
URL: https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
aafc29e534
commit
73c937b47a
1 changed files with 56 additions and 0 deletions
56
cs/remove-sub-folders-from-the-filesystem.cs
Normal file
56
cs/remove-sub-folders-from-the-filesystem.cs
Normal file
|
@ -0,0 +1,56 @@
|
|||
public class Solution {
|
||||
private class Trie<T> {
|
||||
public class TrieNode {
|
||||
public bool Has;
|
||||
public Dictionary<T, TrieNode> Successors;
|
||||
|
||||
public TrieNode() {
|
||||
Has = false;
|
||||
Successors = new Dictionary<T, TrieNode>();
|
||||
}
|
||||
}
|
||||
|
||||
public TrieNode Root = new TrieNode();
|
||||
|
||||
public void Add(IEnumerable<T> path) {
|
||||
var node = Root;
|
||||
foreach (var element in path) {
|
||||
if (!node.Successors.ContainsKey(element)) {
|
||||
node.Successors[element] = new TrieNode();
|
||||
}
|
||||
node = node.Successors[element];
|
||||
}
|
||||
node.Has = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void Reconstruct(
|
||||
List<string> result, List<string> path, Trie<string>.TrieNode node
|
||||
) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.Has) {
|
||||
result.Add(String.Join("/", path));
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var subdirectory in node.Successors) {
|
||||
path.Add(subdirectory.Key);
|
||||
Reconstruct(result, path, subdirectory.Value);
|
||||
path.RemoveAt(path.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public IList<string> RemoveSubfolders(string[] folder) {
|
||||
var trie = new Trie<string>();
|
||||
foreach (var entry in folder) {
|
||||
trie.Add(entry.Split("/"));
|
||||
}
|
||||
|
||||
var result = new List<string>();
|
||||
Reconstruct(result, new List<string>(), trie.Root);
|
||||
return result;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue