
Solution: Using HashMap

- Insertion:
- O(m), O(m) in worst case(we need to insert a total new str)
- Serach:
class Trie {
class Node {
Map<Character, Node> children = new HashMap<>();
boolean isEnd;
Node() {}
}
Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node cur = root;
for (char c : word.toCharArray()) {
if (!cur.children.containsKey(c)) {
cur.children.put(c, new Node());
}
cur = cur.children.get(c);
}
cur.isEnd = true;
}
public boolean search(String word) {
Node cur = root;
for (char c : word.toCharArray()) {
if (!cur.children.containsKey(c)) {
return false;
}
cur = cur.children.get(c);
}
return cur.isEnd;
}
public boolean startsWith(String prefix) {
Node cur = root;
for (char c : prefix.toCharArray()) {
if (!cur.children.containsKey(c)) {
return false;
}
cur = cur.children.get(c);
}
return true;
}
}
Solution: using array
- 包含三个单词 "sea","sells","she" 的 Trie

class Trie {
public Node root;
public class Node {
public Node[] children;
public boolean isEnd;
public Node() {
children = new Node[26];
}
}
public Trie() {
root = new Node();
}
public void insert(String word) {
Node node = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (node.children[index] == null) {
node.children[index] = new Node();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
Node node = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
Node node = root;
for (int i = 0; i < prefix.length(); i++) {
int index = prefix.charAt(i) - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return true;
}
}