Skip to content

Commit a404177

Browse files
committed
solve implement trie prefix tree
1 parent 01df823 commit a404177

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Trie {
2+
Set<String> dict;
3+
4+
public Trie() {
5+
dict = new TreeSet<>();
6+
}
7+
8+
public void insert(String word) {
9+
dict.add(word);
10+
}
11+
12+
public boolean search(String word) {
13+
if(dict.contains(word)) return true;
14+
return false;
15+
}
16+
17+
public boolean startsWith(String prefix) {
18+
for(String saved : dict){
19+
int count = 0;
20+
if(prefix.compareTo(saved) > 0) continue;
21+
if(prefix.length() > saved.length()) continue;
22+
23+
for(int i = 0; i < prefix.length(); i++){
24+
if(prefix.charAt(i) != saved.charAt(i)) break;
25+
count++;
26+
}
27+
if(count == prefix.length()) return true;
28+
}
29+
return false;
30+
}
31+
}
32+
33+
/**
34+
* Your Trie object will be instantiated and called as such:
35+
* Trie obj = new Trie();
36+
* obj.insert(word);
37+
* boolean param_2 = obj.search(word);
38+
* boolean param_3 = obj.startsWith(prefix);
39+
*/
40+

0 commit comments

Comments
 (0)