C# implementation


  • 0
    C

    C# Implementation, refer https://discuss.leetcode.com/topic/33972/java-my-solution-with-brief-explanations-15ms-beats-95

        class TrieNode
        {
            public bool isEnd = false;
            public TrieNode[] children =  new TrieNode[26];
    
            public TrieNode()
            {
            }
        }
    
        class Trie
        {
            private TrieNode root;
    
            public Trie()
            {
                root = new TrieNode();
            }
    
            public void Insert(string word)
            {
                TrieNode cur = root;
    
                for (int i = 0; i < word.Length; i++)
                {
                    int id = word[i] - 'a';
                    if (cur.children[id] == null)
                    {
                        cur.children[id] = new TrieNode();
                    }
    
                    cur = cur.children[id];
                }
    
                cur.isEnd = true;
            }
    
            public bool Search(string word)
            {
                TrieNode node = SearchNode(word);
                return node != null && node.isEnd;
            }
    
            public bool StartsWith(string word)
            {
                TrieNode node = SearchNode(word);
                return node != null;
            }
    
            private TrieNode SearchNode(string word)
            {
                TrieNode cur = root;
                int i = 0;
    
                while (i < word.Length)
                {
                    cur = cur.children[word[i++] - 'a'];
                    if (cur == null)
                    {
                        return null;
                    }
                }
    
                return cur;
            }
        }
    

Log in to reply
 

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