/*
1 建立一个数据结构 有根结点 并且每个节点有26个子节点 同时能标记 true或者false;
2 构造函数正常初始化;
3 插入单词的时候 需要按位遍历 由于数据结构是存放26位的数组 ,每次拿到一位字母 按照与‘a’的差值存放进入数组即可,需要以树状的形态存储,当遍历完整个单词 把最后一位的TrieNode里面的isEnd标记为true;
4 查找的时候 同样是按照差值查看位置是否为空 为空则返回false 不为空就向下一层遍历,结束后返回isEnd的值;
5 只查找前缀则 基于第四步 最后不去判断isEnd的值就好;
*/
class TrieNode {
public TrieNode[] trieNode = new TrieNode[26];
public boolean isEnd = false;
}
class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode temp = root;
for(int i = 0; i < word.length(); i++) {
int diff = word.charAt(i) - 'a';
if(temp.trieNode[diff] == null) {
temp.trieNode[diff] = new TrieNode();
}
temp = temp.trieNode[diff];
}
temp.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode temp = root;
for(int i = 0; i < word.length(); i++) {
int diff = word.charAt(i) - 'a';
if(temp.trieNode[diff] == null) {
return false;
}
temp = temp.trieNode[diff];
}
return temp.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode temp = root;
for(int i = 0; i < prefix.length(); i++) {
int diff = prefix.charAt(i) - 'a';
if(temp.trieNode[diff] == null) {
return false;
}
temp = temp.trieNode[diff];
}
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);
*/