Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 46d3f9f

Browse files
Add Solution.java to problems 0208
1 parent a0f2bc0 commit 46d3f9f

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class Trie {
2+
3+
class TrieNode {
4+
5+
private TrieNode[] links;
6+
7+
private final int R = 26;
8+
9+
private boolean isEnd;
10+
11+
public TrieNode() {
12+
links = new TrieNode[R];
13+
}
14+
15+
public boolean containsKey(char ch) {
16+
return links[ch -'a'] != null;
17+
}
18+
19+
public TrieNode get(char ch) {
20+
return links[ch -'a'];
21+
}
22+
23+
public void put(char ch, TrieNode node) {
24+
links[ch -'a'] = node;
25+
}
26+
27+
public void setEnd() {
28+
isEnd = true;
29+
}
30+
31+
public boolean isEnd() {
32+
return isEnd;
33+
}
34+
}
35+
36+
private TrieNode root;
37+
38+
public Trie() {
39+
root = new TrieNode();
40+
}
41+
42+
public void insert(String word) {
43+
TrieNode node = root;
44+
for (int i = 0; i < word.length(); i++) {
45+
char currentChar = word.charAt(i);
46+
if (!node.containsKey(currentChar)) {
47+
node.put(currentChar, new TrieNode());
48+
}
49+
node = node.get(currentChar);
50+
}
51+
node.setEnd();
52+
}
53+
54+
private TrieNode searchPrefix(String word) {
55+
TrieNode node = root;
56+
for (int i = 0; i < word.length(); i++) {
57+
char curLetter = word.charAt(i);
58+
if (node.containsKey(curLetter)) {
59+
node = node.get(curLetter);
60+
} else {
61+
return null;
62+
}
63+
}
64+
return node;
65+
}
66+
67+
public boolean search(String word) {
68+
TrieNode node = searchPrefix(word);
69+
return node != null && node.isEnd();
70+
}
71+
72+
public boolean startsWith(String prefix) {
73+
TrieNode node = searchPrefix(prefix);
74+
return node != null;
75+
}
76+
}

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /