解题思路
前缀树模板。
代码
class Trie {
private Trie[] next;
boolean isEnd;
/**
* Initialize your data structure here.
*/
public Trie() {
next = new Trie[26];
isEnd = false;
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
int length = word.length();
Trie now = this;
for (int i = 0; i < length; i++) {
int index = word.charAt(i) - 'a';
if (now.next[index] == null) {
now.next[index] = new Trie();
}
now = now.next[index];
}
now.isEnd = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
int length = word.length();
Trie now = this;
for (int i = 0; i < length; i++) {
int index = word.charAt(i) - 'a';
if (now.next[index] == null) return false;
now = now.next[index];
}
return now.isEnd;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
int length = prefix.length();
Trie now = this;
for (int i = 0; i < length; i++) {
int index = prefix.charAt(i) - 'a';
if (now.next[index] == null) return false;
now = now.next[index];
}
return true;
}
}