Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
题意:构造一个字典树,并实现insert方法,search方法,startWith方法
注意:
- insert方法:插入的过程中注意标注节点是字符串结尾节点还是前缀节点
- search方法:遍历树,需要判断是否是字符串结尾节点
- startWith方法:与search方法类似,但是不需要判断节点是字符串结尾节点还是前缀节点
class TrieNode {
// Initialize your data structure here.
public char key;
public TrieNode[] nodes;
//flag == 1 表示是字符串
//flag == 0 表示是前缀
public int flag;
public TrieNode() {
key='\0';
nodes = new TrieNode[26];
}
public TrieNode(char c){
key = c;
nodes = new TrieNode[26];
flag = 0;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode p = root;
for(int i = 0; i < word.length();i++){
char c = word.charAt(i);
if(p.nodes[c-'a'] == null){
TrieNode tmp = new TrieNode(c);
p.nodes[c - 'a'] = tmp;
p = tmp;
}else{
p = p.nodes[c-'a'];
}
}
//更新节点标志
p.flag = 1;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode p = root;
for(int i = 0; i < word.length();i++){
char c = word.charAt(i);
if(p.nodes[c-'a'] == null){
return false;
}else{
p = p.nodes[c-'a'];
}
}
if(p.flag == 1){
return true;
}else{
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i = 0; i < prefix.length();i++){
char c = prefix.charAt(i);
if(p.nodes[c-'a'] == null){
return false;
}else{
p = p.nodes[c-'a'];
}
}
return true;
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");