Implement a trie withinsert,search, andstartsWithmethods.
Note:
You may assume that all inputs are consist of lowercase lettersa-z.
2. Implementation
classTrie {classTrieNode {char val;boolean isWord;TrieNode[] childNode;publicTrieNode(char val) {this.val= val; childNode =newTrieNode[26]; } }TrieNode root; /** Initialize your data structure here. */publicTrie() { root =newTrieNode(' '); } /** Inserts a word into the trie. */publicvoidinsert(String word) {if (word ==null||word.length() ==0) {return; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {curNode.childNode[index] =newTrieNode(c); } curNode =curNode.childNode[index]; }curNode.isWord=true; } /** Returns if the word is in the trie. */publicbooleansearch(String word) {if (word ==null||word.length() ==0) {returnfalse; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {returnfalse; } curNode =curNode.childNode[index]; }returncurNode.isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */publicbooleanstartsWith(String prefix) {if (prefix ==null||prefix.length() ==0) {returnfalse; }TrieNode curNode = root;for (char c :prefix.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {returnfalse; } curNode =curNode.childNode[index]; }returntrue; }}/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
3. Time & Space Complexity
时间复杂度: inset:O(L), search: O(L), startsWith: O(L), L 为输入string的长度