我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/
题目描述:
知识点:Trie、哈希表
思路:定义一个新的内部类Node,用isWord标记该位置是否是一个单词,用next指向下一个节点
insert、search和startWith操作的时间复杂度均是O(n),其中n为待插入字符串或待查询字符串或前缀的长度。
JAVA代码:
class Trie {
private class Node{
private boolean isWord;
private HashMap<Character, Node> next;
public Node(boolean isWord) {
this.isWord = isWord;
this.next = new HashMap<>();
}
public Node() {
this(false);
}
}
private Node root;
private int size;
public Trie() {
root = new Node();
size = 0;
}
public void insert(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.next.get(c) == null) {
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
if(!cur.isWord) {
cur.isWord = true;
size++;
}
}
public boolean search(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return cur.isWord;
}
public boolean startsWith(String prefix) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if(cur.next.get(c) == null) {
return false;
}
cur = cur.next.get(c);
}
return true;
}
}
LeetCode解题报告: