-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
95 lines (86 loc) · 2.29 KB
/
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
interface IChildren {
[key: string]: TrieNode;
}
class TrieNode {
public isWord: boolean;
public childrens: IChildren;
constructor() {
this.isWord = false;
this.childrens = {};
}
}
class Trie {
private root: TrieNode;
constructor() {
this.root = new TrieNode();
}
public insertTrie(word: string) {
let currentNode = this.root;
for (let i = 0; i < word.length; i++) {
if (!currentNode.childrens[word[i]]) {
currentNode.childrens[word[i]] = new TrieNode();
}
currentNode = currentNode.childrens[word[i]];
}
currentNode.isWord = true;
}
public searchTrie(word: string): boolean {
let currentNode = this.root;
for (let i = 0; i < word?.length; i++) {
if (!currentNode.childrens[word[i]]) {
return false;
}
currentNode = currentNode.childrens[word[i]];
}
return currentNode.isWord;
}
public startWith(startWithChars: string): boolean {
const currentNode = this.getNode(startWithChars);
return currentNode != null;
}
public stringSuggestion(startWithChars: string): string[] {
const suggestedString: string[] = [];
const currentNode = this.getNode(startWithChars);
if (currentNode != null) {
this.getSuggenstions(suggestedString, startWithChars, currentNode);
}
return suggestedString;
}
private getNode(word: string): TrieNode | null {
let currentNode = this.root;
for (let i = 0; i < word?.length; i++) {
if (!currentNode.childrens[word[i]]) {
return null;
}
currentNode = currentNode.childrens[word[i]];
}
return currentNode;
}
private getSuggenstions(
suggestion: string[],
matchingWord: string,
currentNode: TrieNode
) {
const keys = Object.keys(currentNode.childrens);
if (currentNode.isWord) {
suggestion.push(matchingWord);
}
if (keys?.length === 0) {
return;
}
for (let i = 0; i < keys.length; i++) {
this.getSuggenstions(
suggestion,
matchingWord + keys[i],
currentNode.childrens[keys[i]]
);
}
}
}
const triesObj = new Trie();
triesObj.insertTrie('apple');
triesObj.insertTrie('appk');
triesObj.insertTrie('akon');
triesObj.insertTrie('yup');
console.log(triesObj.searchTrie('apple'));
console.log(triesObj.stringSuggestion('a'));