Leetcode 208、实现Trie(前缀树)
使用数组实现前缀树
-
insert()
向前缀树里面插入字符串
遍历当前要插入的字符串,查看当前数组对应的位置是否为空如果为空,temp[curr] = new Trie();并且temp = temp[curr].children;
就是继续向下添加;如果当前位置是字符串的最后一个位置,那么对应的Trie
里面的endWith = true;如果不为空,就直接temp = temp[curr].children,并且如果一直都不为空,
那么遍历到最后一个字符的时候,需要把对应的endWith设置为true,
即:temp[curr].endWith = true; -
search()
遍历当前要查找的字符串,如果当前位置为空,直接返回false;
如果不为空,继续向下遍历前缀树;如果当前是字符串的最后
一个字符,判断当前temp[curr].endWith是否为true,不是的话返回false。 -
startsWith()
这里查询的是前缀,所以不需要判断endWith
遍历要查找的prefix,如果Trie当前位置为空,返回false;
不为空继续向下遍历字符串和Trie。
class Trie {
Trie[] children;
boolean endWith;
public Trie() {
children = new Trie[26];
endWith = false;
}
/**
向前缀树里面插入字符串
遍历当前要插入的字符串,查看当前数组对应的位置是否为空
如果为空,temp[curr] = new Trie();并且temp = temp[curr].children;
就是继续向下添加;如果当前位置是字符串的最后一个位置,那么对应的Trie
里面的endWith = true;
如果不为空,就直接temp = temp[curr].children,并且如果一直都不为空,
那么遍历到最后一个字符的时候,需要把对应的endWith设置为true,
即:temp[curr].endWith = true;
**/
public void insert(String word) {
Trie[] temp = children;
for(int i = 0; i < word.length(); i++) {
int curr = word.charAt(i) - 'a';
if(temp[curr] == null) {
temp[curr] = new Trie();
if(i == word.length() - 1) {
temp[curr].endWith = true;
}
temp = temp[curr].children;
}else{
if(i == word.length() - 1) {
temp[curr].endWith = true;
}
temp = temp[curr].children;
}
}
}
/**
遍历当前要查找的字符串,如果当前位置为空,直接返回false;
如果不为空,继续向下遍历前缀树;如果当前是字符串的最后
一个字符,判断当前temp[curr].endWith是否为true,不是的
话返回false。
**/
public boolean search(String word) {
Trie[] temp = children;
for(int i = 0; i < word.length(); i++) {
int curr = word.charAt(i) - 'a';
if(temp[curr] != null) {
if(i == word.length() - 1 && temp[curr].endWith) {
return true;
}
temp = temp[curr].children;
}else if(i != word.length() - 1 && temp[curr] == null) {
return false;
}
}
return false;
}
/**
这里查询的是前缀,所以不需要判断endWith
遍历要查找的prefix,如果Trie当前位置为空,返回false;
不为空继续向下遍历字符串和Trie。
**/
public boolean startsWith(String prefix) {
Trie[] temp = children;
for(int i = 0; i < prefix.length(); i++) {
int curr = prefix.charAt(i) - 'a';
if(temp[curr] != null) {
if(i == prefix.length() - 1) {
return true;
}
temp = temp[curr].children;
}else if(i != prefix.length() - 1 && temp[curr] == null) {
return false;
}
}
return false;
}
}