小白太久没有做算法题了,,,以博客记录学习过程的方法来督促自己,加油,奥利给!
class TrieNode{
TrieNode [] child; //孩子数组,下标对应字母,如果出现对应下标的字母就将该孩子实例化
boolean isEnd; //判断是否为该单词的最后一个字母
public TrieNode(){
this.child=new TrieNode[26];
this.isEnd=false;
}
}
//leetcode submit region begin(Prohibit modification and deletion)
class Trie {
TrieNode root;
/** Initialize your data structure here. */
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++){
if (p.child[word.charAt(i)-'a']==null){
p.child[word.charAt(i)-'a']=new TrieNode();
}
p=p.child[word.charAt(i)-'a']; //root变为孩子
}
p.isEnd=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode p=root;
for (int i=0;i<word.length();i++){
if (p.child[word.charAt(i)-'a']!=null){
p=p.child[word.charAt(i)-'a'];
}else {
return false;
}
}
return p.isEnd==true;
}
/** 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++){
if (p.child[prefix.charAt(i)-'a']!=null){
p=p.child[prefix.charAt(i)-'a'];
}else {
return false;
}
}
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);
*/
//leetcode submit region isEnd(Prohibit modification and deletion)