Skip to content

Commit 062daa3

Browse files
author
Jiang Haifeng
committed
三向单词查找树
1 parent 9f963f1 commit 062daa3

2 files changed

Lines changed: 102 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
- [区域和检索 - 数组可修改_pending](./SegmentTree/src/SegmentTree.java)
2727
- 【字典树】
2828
* [Trie](./Trie/src/Trie.java)
29+
* [TSTrie - 三向单词查找树](./Trie/src/TSTrie.java)
2930
* [WordDictionary - LeetCode_zh_211](./Trie/src/WordDictionary.java)
3031
* [MapSum - LeetCode_en_677](./Trie/src/MapSum.java)
3132
* [实现 Trie (前缀树) - LeetCode_zh_208](./Trie/src/Trie.java)

Trie/src/TSTrie.java

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
2+
public class TSTrie { //<C>
3+
/*
4+
*
5+
*
6+
*
7+
* 三向单词查找树
8+
命题4:
9+
描述:有N个平均长度为w的字符串构造的三向单词查找树中的链接总数在3N到3Nw之间。
10+
证明:同命题3。
11+
备注:三向单词查找树实际使用的内存空间一般都低于由每个字符三个链接得到的上界,因为有相同前缀的键会共享树种的高层结点。
12+
* */
13+
private class Node {
14+
public char c;
15+
public int val;
16+
public Node left, mid, right;
17+
18+
public Node(char c, int val, Node left, Node mid, Node right) {
19+
this.c = c;
20+
this.val = val;
21+
this.left = left;
22+
this.mid = mid;
23+
this.right = right;
24+
}
25+
26+
public Node(char c) {
27+
this(c, -1, null, null, null);
28+
}
29+
30+
public Node() {
31+
this('\0', -1, null, null, null);
32+
}
33+
}
34+
35+
private Node root;
36+
private int size;
37+
38+
39+
public TSTrie() {
40+
root = null;
41+
size = 0;
42+
}
43+
44+
public int getSize() {
45+
return size;
46+
}
47+
48+
private Node add(Node cur, String key, int val, int d) {
49+
char c = key.charAt(d);
50+
if (cur == null) {
51+
cur = new Node(c);
52+
}
53+
if (cur.c > c) {
54+
cur.left = add(cur.left, key, val, d);
55+
} else if (cur.c < c) {
56+
cur.right = add(cur.right, key, val, d);
57+
} else if (d < key.length() - 1) {
58+
cur.mid = add(cur.mid, key, val, d + 1);
59+
} else {
60+
cur.val = val;
61+
}
62+
return cur;
63+
}
64+
65+
public void add(String key, int val) {
66+
root = add(root, key, val, 0);
67+
}
68+
69+
public int get(String key) {
70+
Node cur = root;
71+
for (int i = 0; i < key.length(); i++) {
72+
char c = key.charAt(i);
73+
if (cur == null) {
74+
return -1;
75+
}
76+
if (c < cur.c) {
77+
cur = cur.left;
78+
i--;
79+
} else if (c > cur.c) {
80+
cur = cur.right;
81+
i--;
82+
} else {
83+
if (i == key.length() - 1)
84+
return cur.val;
85+
cur = cur.mid;
86+
}
87+
}
88+
return cur.val;
89+
}
90+
91+
public static void main(String[] args) {
92+
TSTrie tsTrie = new TSTrie();
93+
tsTrie.add("apple", 1);
94+
tsTrie.add("applc", 2);
95+
System.out.println(tsTrie.get("app"));
96+
System.out.println(tsTrie.get("apple"));
97+
System.out.println(tsTrie.get("applc"));
98+
System.out.println(tsTrie.get("appld"));
99+
System.out.println(tsTrie.get("appldd"));
100+
}
101+
}

0 commit comments

Comments
 (0)