-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
31 lines (29 loc) · 851 Bytes
/
index.ts
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
import { PrefixTree } from "../implement-trie-prefix-tree/PrefixTree.ts";
import { PrefixTreeInsert, PrefixTreeSearchPrefix } from "../mod.ts";
export default function replaceWords(
dictionary: string[],
sentence: string,
): string {
const root = PrefixTree();
dictionary.forEach((word) =>
PrefixTreeInsert(root, word, {
stop: (node) => node.isEnd,
})
);
const words = sentence.split(" ");
return words
.map((word) => {
let index = -1;
const node = PrefixTreeSearchPrefix(root, word, {
stop: (node) => node.isEnd,
each() {
index++;
},
});
if (!node) {
return word;
}
return word.slice(0, index);
})
.join(" ");
}