(AC) c# single array solution


  • 0
    G
    public class TrieNode {
        
        public TrieNode[] children = new TrieNode[26];
        public bool isWord = false;
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void Insert(String word) {
            TrieNode current = root;
            
            foreach (char c in word) {
                int index = c - 'a';
                if (current.children[index] == null) {
                    current.children[index] = new TrieNode();
                }
                
                current = current.children[index];
            }
            
            current.isWord = true;
        }
    
        // Returns if the word is in the trie.
        public bool Search(string word) {
            var node = MoveToNode(word);
            
            return node != null && node.isWord; 
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public bool StartsWith(string word) {
            var node = MoveToNode(word);
            
            return node != null;
        }
        
        private TrieNode MoveToNode(string str) {
            TrieNode current = root;
            
            foreach (char c in str) {
                int index = c - 'a';
                if (current.children[index] == null) {
                    return null;
                }
                
                current = current.children[index];
            }
            
            return current;
        }
    }
    

Log in to reply
 

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