From 73c937b47af41113e69998fc2c27010e31e48bed Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 26 Oct 2024 00:13:37 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1233.=20Remove=20Sub-Folders?= =?UTF-8?q?=20from=20the=20Filesystem=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/ Signed-off-by: Matej Focko --- cs/remove-sub-folders-from-the-filesystem.cs | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 cs/remove-sub-folders-from-the-filesystem.cs diff --git a/cs/remove-sub-folders-from-the-filesystem.cs b/cs/remove-sub-folders-from-the-filesystem.cs new file mode 100644 index 0000000..ebd7c3e --- /dev/null +++ b/cs/remove-sub-folders-from-the-filesystem.cs @@ -0,0 +1,56 @@ +public class Solution { + private class Trie { + public class TrieNode { + public bool Has; + public Dictionary Successors; + + public TrieNode() { + Has = false; + Successors = new Dictionary(); + } + } + + public TrieNode Root = new TrieNode(); + + public void Add(IEnumerable 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 result, List path, Trie.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 RemoveSubfolders(string[] folder) { + var trie = new Trie(); + foreach (var entry in folder) { + trie.Add(entry.Split("/")); + } + + var result = new List(); + Reconstruct(result, new List(), trie.Root); + return result; + } +}