leetcode解题: Implement Trie (Prefix Tree) (208)

Implement a trie with insert, search, and startsWith methods.

解法1:

本题主要是考察Trie树的基本概念,可以参考Wiki的解释。 实现的时候,每一个node的children可以用一个map来实现,做insert或者是search的时候可以用一个current的指针从root开始不停的往下搜索。
比较直观,并没有难度。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
isWord = false;
}
unordered_map<char, TrieNode*> children;
bool isWord;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode* cur = root;
for (char c: word) {
if (!cur->children.count(c)) {
cur->children[c] = new TrieNode();
}
cur = cur->children[c];
}
cur->isWord = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* cur = root;
for (char c: word) {
if (!cur->children.count(c)) {
return false;
}
cur = cur->children[c];
}
return cur->isWord;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* cur = root;
for (char c: prefix) {
if (!cur->children.count(c)) {
return false;
}
cur = cur->children[c];
}
return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class TrieNode {
Map<Character, TrieNode> map;
boolean isWord;
public TrieNode() {
this.map = new HashMap<Character, TrieNode>();
}
};
public class Trie {
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
if (!current.map.containsKey(c)) {
current.map.put(c, new TrieNode());
}
current = current.map.get(c);
}
current.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
if (!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return current.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode current = root;
for (char c: prefix.toCharArray()) {
if (!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
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);
*/