Accepted solution for C#


  • 0
    P
    class TrieNode {
        public bool IsWord { get; set; }
    
        public TrieNode[] Children { get; set; }
    
        public void Insert(string word, int index)
        {
            if (index == word.Length)
            {
                IsWord = true;
                return;
            }
    
            var i = word[index] - 'a';
    
            if (Children == null)
            {
                Children = new TrieNode[26];
            }
    
            if (Children[i] == null)
            {
                Children[i] = new TrieNode();
            }
    
            Children[i].Insert(word, index + 1);
        }
    
        public bool Search(string word, int index)
        {
            if (index == word.Length)
            {
                return IsWord;
            }
    
            var i = word[index] - 'a';
    
            if (Children == null
                || Children[i] == null)
            {
                return false;
            }
    
            return Children[i].Search(word, index + 1);
        }
    
        public bool StartsWith(string word, int index)
        {
            if (index == word.Length)
            {
                return true;
            }
    
            var i = word[index] - 'a';
    
            if (Children == null
                || Children[i] == null)
            {
                return false;
            }
    
            return Children[i].StartsWith(word, index + 1);
        }
    }
    
    public class Trie {
        private readonly TrieNode _root;
    
        public Trie()
        {
            _root = new TrieNode();
        }
    
        public void Insert(string word)
        {
            _root.Insert(word, 0);
        }
    
        public bool Search(string word)
        {
            return _root.Search(word, 0);
        }
    
        public bool StartsWith(string word)
        {
            return _root.StartsWith(word, 0);
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.Insert("somestring");
    // trie.Search("key");

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.