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