Back to problems
COMP2521
Trie: count stored words
Trie: count how many words are stored
Insert several lowercase words into a Trie and print the number of distinct words.
Key idea: in a Trie each complete word corresponds to one node marked isEnd=true; all other nodes are just prefixes on the way. So the word count equals the number of isEnd nodes, independent of total node count; inserting the same word twice still counts once.
countWords (which recursively counts isEnd nodes) is provided. You only complete insert: descend per character, create missing edges, and mark the final node isEnd=true — forget it and nothing gets counted.
Input
- Line 1: number of words
n. - Next
nlines: one lowercase word (a-z) each.
Output
- One line: the number of distinct words.
Example: inserting cat car card dog do (5 distinct words) -> 5.
Samples
stdin
5 cat car card dog do
expected
5
stdin
4 to to tea ten
expected
3
c-dcc
14