Skip to content

Commit da2cf92

Browse files
committed
add trie
1 parent 9f7f863 commit da2cf92

3 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎JavaScript/Trie/Test.js‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// 测试字典树
2+
const Trie = require('./Trie');
3+
var t = new Trie();
4+
t.add('happy');
5+
t.add('birthday');
6+
t.add('cat');
7+
t.add('catch');
8+
console.log(t.getSize());
9+
console.log(t.isPrefix('ca'));

‎JavaScript/Trie/Trie.js‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// 定义节点
2+
class Node {
3+
constructor(isWord=false) {
4+
this.isWord = isWord;
5+
this.next = new Map();
6+
}
7+
}
8+
// 字典树
9+
module.exports = class Trie{
10+
constructor() {
11+
this.root = new Node();
12+
this.size = 0;
13+
}
14+
// 获取Trie中存储的单词数量
15+
getSize() {
16+
return this.size;
17+
}
18+
// 向Trie中添加一个新的单词word
19+
add(word) {
20+
// 非递归写法,字符串拆成字符
21+
let cur = this.root;
22+
for(let i = 0;i < word.length; i++) {
23+
let c = word.charAt(i);
24+
if(cur.next.get(c) === undefined) {
25+
cur.next.set(c, new Node());
26+
}
27+
cur = cur.next.get(c); // 走到下一个节点
28+
}
29+
// 这个节点以前不表示单词结尾
30+
if(!cur.isWord) {
31+
cur.isWord = true;
32+
this.size++;
33+
}
34+
}
35+
// 查询单词word是否在Trie中
36+
contains(word) {
37+
let cur = root;
38+
for(let i = 0;i < word.length; i++) {
39+
let c = wrod.charAt(i);
40+
if(cur.next.get(c) === null)
41+
return false;
42+
cur = cur.next.get(c);
43+
}
44+
// 比如trie中有panda,查pan。查到节点,但是并没有这个单词
45+
return cur.isWord;
46+
}
47+
// 前缀查询
48+
isPrefix(prefix) {
49+
let cur = this.root;
50+
for(let i = 0; i < prefix.length; i++) {
51+
let c = prefix.charAt(i);
52+
if(cur.next.get(c) === undefined)
53+
return false;
54+
cur = cur.next.get(c);
55+
}
56+
return true;
57+
}
58+
}

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@
4444
- [线段树I](./JavaScript/SegmentTree/SegmentTree.js)
4545
- [线段树II](./JavaScript/SegmentTree/SegmentTreeII.js)
4646

47+
### 字典树:
48+
一种树型结构,用于字符串匹配
49+
50+
- [字典树](./JavaScript/Trie/Trie.js)
51+
4752
### 图论:
4853

4954
- [图的实现](./JavaScript/Graph/Graph.js)

0 commit comments

Comments
 (0)