-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
52 lines (47 loc) · 1.32 KB
/
Main.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
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
}
}
class TrieNode {
int val;
TrieNode[] children;
boolean isWord;
public TrieNode(){
children = new TrieNode[26];
}
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode point = root;
for (int i = 0; i < word.length(); i++) {
if(point.children[word.charAt(i) - 'a'] == null)
point.children[word.charAt(i) - 'a'] = new TrieNode();
point = point.children[word.charAt(i) - 'a'];
}
point.isWord = true;
}
public boolean search(String word) {
TrieNode point = root;
for (int i = 0; i < word.length(); i++) {
if(point.children[word.charAt(i) - 'a'] == null)
return false;
point = point.children[word.charAt(i) - 'a'];
}
return point.isWord;
}
public boolean startsWith(String prefix) {
TrieNode point = root;
for (int i = 0; i < prefix.length(); i++) {
if(point.children[prefix.charAt(i) - 'a'] == null)
return false;
point = point.children[prefix.charAt(i) - 'a'];
}
return true;
}
}