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:
Matej Focko 2024-10-26 00:13:37 +02:00
parent aafc29e534
commit 73c937b47a
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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;
}
}