题意:实现Trie
思路:利用Trie的数据结构实现插入,查询,和prefix,具体见代码
思想:Trie
复杂度:时间O(n),空间O(n)
class Node {
// 记录所有的子节点
public Node[] nodes = new Node[26];
// 当前节点是否是叶节点
public boolean isLeaf;
// 当前节点的字符值
public char val;
public Node(boolean isLeaf, char val) {
this.isLeaf = isLeaf;
this.val = val;
}
}
class Trie {
// Trie的根节点
Node roots;
/** Initialize your data structure here. */
public Trie() {
roots = new Node(false, ' ');
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node root = roots;
// 遍历字符查找每一个节点的下一个字符节点是否存在
// 如果存在就更新root,否则创建新节点
for(int i=0;i<word.length();i++) {
int index = word.charAt(i) - 'a';
if(root.nodes[index] == null) {
Node temp = new Node(false, word.charAt(i));
root.nodes[index] = temp;
root = temp;
} else
root = root.nodes[index];
}
root.isLeaf = true;;
}
public boolean search(String word) {
Node root = roots;
// 遍历字符查找每一个节点的下一个字符节点是否存在
for(int i=0;i<word.length();i++) {
int index = word.charAt(i) - 'a';
if(root.nodes[index] == null)
return false;
root = root.nodes[index];
}
// 返回最后的节点是否是叶子节点
return root.isLeaf;
}
public boolean startsWith(String prefix) {
Node root = roots;
// 遍历字符查找每一个节点的下一个字符节点是否存在
for(int i=0;i<prefix.length();i++) {
int index = prefix.charAt(i) - 'a';
if(root.nodes[index] == null)
return false;
root = root.nodes[index];
}
return true;
}
}
网友评论