Example #1
0
    //Insert a word into the Trie. O(m) time/space complexity. m is word length
    public void Insert(String word)
    {
        TrieArrayNode node = root;

        for (int i = 0; i < word.Length; ++i)
        {
            if (!node.ContainsKey(word[i]))
            {
                node.Put(word[i], new TrieArrayNode());
            }
            node = node.Get(word[i]);
        }
        node.SetEnd();
    }
Example #2
0
    //search a prefix(or whole key) in trie and
    //returns the node where search ends
    //O(m) time complexity, O(1) space complexity
    private TrieArrayNode SearchPrefix(string prefix)
    {
        TrieArrayNode node = root;

        for (int i = 0; i < prefix.Length; ++i)
        {
            if (node.ContainsKey(prefix[i]))
            {
                node = node.Get(prefix[i]);
            }
            else
            {
                return(null);
            }
        }
        return(node);
    }
Example #3
0
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    // O(m) time complexity, O(1) space complexity
    public bool StartsWith(string prefix)
    {
        TrieArrayNode node = SearchPrefix(prefix);

        return(node != null);
    }
Example #4
0
    //Search a whole word in the trie
    //Returns if the word is in the trie.
    public bool Search(String word)
    {
        TrieArrayNode node = SearchPrefix(word);

        return(node != null && node.IsEnd());
    }
Example #5
0
 //constructor
 public TrieArray()
 {
     root = new TrieArrayNode();
 }
Example #6
0
 //put a child node in
 public void Put(char ch, TrieArrayNode node)
 {
     children[ch - 'a'] = node;
 }