-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTriePrefixTree.java
66 lines (60 loc) · 1.5 KB
/
TriePrefixTree.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
60
61
62
63
64
65
66
/*https://leetcode.com/problems/implement-trie-prefix-tree/*/
class TrieNode
{
TrieNode[] hash;
boolean isEndOfWord;
TrieNode()
{
hash = new TrieNode[26];
isEndOfWord = false;
}
}
class Trie
{
boolean stopDFS = false;
TrieNode root;
Trie()
{
root = new TrieNode();
}
public void insert(String word)
{
TrieNode temp = root;
for (int i = 0; i < word.length(); ++i)
{
if (temp.hash[word.charAt(i)-'a'] == null)
temp.hash[word.charAt(i)-'a'] = new TrieNode();
temp = temp.hash[word.charAt(i)-'a'];
}
temp.isEndOfWord = true;
}
public boolean search(String word)
{
TrieNode temp = root;
for (int i = 0; i < word.length(); ++i)
{
if (temp.hash[word.charAt(i)-'a'] == null)
return false;
temp = temp.hash[word.charAt(i)-'a'];
}
return temp.isEndOfWord;
}
public boolean startsWith(String prefix)
{
TrieNode temp = root;
for (int i = 0; i < prefix.length(); ++i)
{
if (temp.hash[prefix.charAt(i)-'a'] == null)
return false;
temp = temp.hash[prefix.charAt(i)-'a'];
}
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);
*/