Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
1、每个字母用一个Trie表示,同时isWord表示到目前Trie是否构成一个单词。
public class Trie { public char ch; public Trie[] nextTrie; public boolean isWord; /** Initialize your data structure here. */ public Trie() { nextTrie = new Trie[26]; } public Trie(char ch){ this.ch = ch; nextTrie = new Trie[26]; } /** Inserts a word into the trie. */ public void insert(String word) { Trie[] nextTrie = this.nextTrie; for (int i = 0; i < word.length(); i++){ int num = (int) (word.charAt(i) - 'a'); if (nextTrie[num] == null){ nextTrie[num] = new Trie(word.charAt(i)); } if (i == word.length() - 1){ nextTrie[num].isWord = true; } nextTrie = nextTrie[num].nextTrie; } } /** Returns if the word is in the trie. */ public boolean search(String word) { Trie[] nextTrie = this.nextTrie; for (int i = 0; i < word.length() - 1; i++){ int num = (int) (word.charAt(i) - 'a'); if (nextTrie[num] == null){ return false; } nextTrie = nextTrie[num].nextTrie; } int num = (int) (word.charAt(word.length() - 1) - 'a'); if (nextTrie[num] == null || nextTrie[num].isWord == false){ return false; } else { return true; } } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String word) { Trie[] nextTrie = this.nextTrie; for (int i = 0; i < word.length(); i++){ int num = (int) (word.charAt(i) - 'a'); if (nextTrie[num] == null){ return false; } nextTrie = nextTrie[num].nextTrie; } return true; } } /** * 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); */