If you really want to use trie, then addToTrie() will really be O (k) , where k is the length of the word to be added. constructTrie() will take O (Nk) , where N is the number of words if you just call addToTrie() for each word. However, you do not need to call the addToTrie() function for each word. After you finish adding the word, simply reset the pointer to trie root, then move the pointer when you move your current word, adding characters as you go forward. Pseudocode:
trieNode *curr = trieRoot; for each character c in document if it a word terminator (space etc) add a character at curr signaling the end of the current word ('\0' maybe); curr = trieRoot; else if character is not a separator add character c at curr->next->character[c]; curr = curr->next;
This will give you O (C) time to build a trie, where C is the number of characters in your document.
Now this asks the question: why do you even need to do it? Obviously you figured out a way to detect when a word ended, so why should you add your words in trie? This is unnecessary. The only data structure required is several variables: one to track the current character, one to track the previous character and word count. This is easy to do in O (C) as follows:
char prev = '\0'; char curr; int count = 0; for each character curr if curr is a word separator and prev isn't ++count; prev = curr;
I think it makes no sense to use trie for this problem, it only complicates the situation. I think that if they wanted to test your knowledge of attempts, they would give you a problem in which the try made more sense.
Even if they provided you with the getNextWord() function (you had to use it because you could do it without it), I assume that it returns "\ 0" or something when there are no more words? So why can't you just call him until he returns "\ 0" and counts such words? In any case, the true really doesn't make sense here.
source share