https://leetcode.com/problems/implement-trie-prefix-tree/
Please comment about performance and style.
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings.
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TrieQuestions { /// <summary> /// https://leetcode.com/problems/implement-trie-prefix-tree/ /// </summary> [TestClass] public class TrieTreeImplementation { [TestMethod] public void TrieInsertTest() { Trie trie = new Trie(); trie.Insert("cat"); Assert.IsTrue(trie.Search("cat")); } [TestMethod] public void TriePrefixSearchTest() { Trie trie = new Trie(); trie.Insert("cats"); Assert.IsTrue(trie.StartsWith("cat")); } [TestMethod] public void OneLetterEdgeCaseTest() { Trie trie = new Trie(); trie.Insert("a"); Assert.IsTrue(trie.Search("a")); Assert.IsTrue(trie.StartsWith("a")); } } public class Trie { public TrieNode Head { get; set; } /** Initialize your data structure here. */ public Trie() { Head = new TrieNode(); } /** Inserts a word into the trie. */ public void Insert(string word) { var current = Head; for (int i = 0; i < word.Length; i++) { if (!current.Edges.ContainsKey(word[i])) { current.Edges.Add(word[i], new TrieNode()); } current = current.Edges[word[i]]; } current.IsTerminal = true; } /** Returns if the word is in the trie. */ public bool Search(string word) { var current = Head; for (int i = 0; i < word.Length; i++) { if (!current.Edges.ContainsKey(word[i])) { return false; } current = current.Edges[word[i]]; } return current.IsTerminal == true; } /** Returns if there is any word in the trie that starts with the given prefix. */ public bool StartsWith(string prefix) { var current = Head; for (int i = 0; i < prefix.Length; i++) { if (!current.Edges.ContainsKey(prefix[i])) { return false; } current = current.Edges[prefix[i]]; } return true; } } public class TrieNode { public Dictionary<char, TrieNode> Edges { get; set; } public bool IsTerminal { get; set; } public TrieNode() { Edges = new Dictionary<char, TrieNode>(); } } }