Skip to content

Commit 4249f5b

Browse files
committed
implemet trie
1 parent 662ccdb commit 4249f5b

File tree

3 files changed

+139
-34
lines changed

3 files changed

+139
-34
lines changed

.idea/workspace.xml

Lines changed: 45 additions & 34 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,3 +420,4 @@ codes may not be optimized
420420

421421
1. [Longest Substring with at least k Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/)
422422
1. [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/description/)
423+
1. [Implement Trie (Prefix Trie)](https://leetcode.com/problems/implement-trie-prefix-tree/description/)
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.github.chen0040.leetcode.day20.medium;
2+
3+
4+
/**
5+
* Created by xschen on 15/8/2017.
6+
*
7+
* link: https://leetcode.com/problems/implement-trie-prefix-tree/description/
8+
*/
9+
public class ImplementTrie {
10+
private static class Node {
11+
boolean bit = false;
12+
int key;
13+
Node left;
14+
Node right;
15+
Node mid;
16+
public Node(int key) {
17+
this.key = key;
18+
}
19+
}
20+
21+
public class Trie {
22+
23+
24+
25+
26+
private Node root;
27+
28+
/** Initialize your data structure here. */
29+
public Trie() {
30+
31+
}
32+
33+
/** Inserts a word into the trie. */
34+
public void insert(String word) {
35+
root = insert(root, word, 0);
36+
}
37+
38+
private Node insert(Node x, String word, int d) {
39+
int key = (int)word.charAt(d);
40+
if(x == null) {
41+
x = new Node(key);
42+
}
43+
44+
if(key < x.key){
45+
x.left = insert(x.left, word, d);
46+
} else if(key > x.key) {
47+
x.right = insert(x.right, word, d);
48+
} else {
49+
if(d < word.length()-1) {
50+
x.mid = insert(x.mid, word, d+1);
51+
} else {
52+
x.bit = true;
53+
}
54+
}
55+
56+
return x;
57+
}
58+
59+
/** Returns if the word is in the trie. */
60+
public boolean search(String word) {
61+
Node x = get(root, word, 0);
62+
if(x == null) {
63+
return false;
64+
} else {
65+
return x.bit;
66+
}
67+
}
68+
69+
private Node get(Node x, String word, int d) {
70+
if(x == null) {
71+
return null;
72+
}
73+
int key = (int)word.charAt(d);
74+
if(key < x.key) {
75+
return get(x.left, word, d);
76+
} else if(key > x.key) {
77+
return get(x.right, word, d);
78+
} else {
79+
if(d == word.length()-1) {
80+
return x;
81+
} else {
82+
return get(x.mid, word, d+1);
83+
}
84+
}
85+
}
86+
87+
/** Returns if there is any word in the trie that starts with the given prefix. */
88+
public boolean startsWith(String prefix) {
89+
Node x = get(root, prefix, 0);
90+
return x != null;
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)