C# solution: TrieNode array


  • 0
    B
    public class Trie 
    {
    	class TrieNode
    	{
    		public TrieNode[] nodes = new TrieNode[26];
    		public bool IsEnd = false;
    	}
    
    	private TrieNode _root;
    
        /** Initialize your data structure here. */
        public Trie() 
    	{
            _root = new TrieNode();
        }
        
        /** Inserts a word into the trie. */
        public void Insert(string word) 
    	{
    		var cur = _root;
            foreach(var c in word)
    		{
    			int index = c-'a';
    
    			if (cur.nodes[index] == null) cur.nodes[index] = new TrieNode();
    
    			cur = cur.nodes[index];
    		}
    
    		cur.IsEnd = true;
        }
        
        /** Returns if the word is in the trie. */
        public bool Search(string word) 
    	{
            var cur = _root;
    
    		foreach(var c in word)
    		{
    			int index = c-'a';
    
    			if (cur.nodes[index] == null) return false;
    
    			cur = cur.nodes[index];
    		}
    
    		return cur.IsEnd;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public bool StartsWith(string prefix) 
    	{
            var cur = _root;
    
    		foreach(var c in prefix)
    		{
    			int index = c-'a';
    
    			if (cur.nodes[index] == null) return false;
    
    			cur = cur.nodes[index];
    		}
    
    		return true;
        }
    }
    

Log in to reply
 

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