implement-trie
Problem
Problem Description
Solution
First understand what is trie, please read Trie (Wiki).
Now define TrieNode with char, isWord, children. 1. do insert:
iterate through each char in word, check whether current char ch in current node's children. if not, create new TrieNode(ch), put into current node children, other wise do nothing
then reset current node as curr.children.get(ch).
after word, set current node isWord = true.
do search:
iterate through each char in word, for each ch:
if ch is in current node children, continue, if not in current node's children, return false. terminate early.
reset current node as curr.children.get(ch), (go next level)
until at last char, check current node isWord is true or not, if isWord = true, return true. otherwise no word in trie.
do prefix search:
same search steps as search word.
at last step, return true (meaning it has prefix, do need to check isWord).
For example:
Complexity Analysis
insert(word): O(n) -- n is the length of word
search(word): O(n) -- n is the length of word
Code
Last updated