-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0648-replace-words.js
More file actions
76 lines (65 loc) · 1.96 KB
/
0648-replace-words.js
File metadata and controls
76 lines (65 loc) · 1.96 KB
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
class TrieNode {
constructor() {
this.childNodes = new Map();
this.isRootTerminus = false;
}
}
class TrieStructure {
constructor() {
this.trieBase = new TrieNode();
}
insertWord(wordToInsert) {
let currentPositionNode = this.trieBase;
for (const charSymbol of wordToInsert) {
if (!currentPositionNode.childNodes.has(charSymbol)) {
currentPositionNode.childNodes.set(charSymbol, new TrieNode());
}
currentPositionNode = currentPositionNode.childNodes.get(charSymbol);
}
currentPositionNode.isRootTerminus = true;
}
findShortestRoot(searchTargetWord) {
let navigatorNode = this.trieBase;
let currentStemBuilder = [];
let shortestRootFound = null;
for (
let elementPosition = 0;
elementPosition < searchTargetWord.length;
elementPosition++
) {
const charComponent = searchTargetWord[elementPosition];
if (!navigatorNode.childNodes.has(charComponent)) {
break;
}
navigatorNode = navigatorNode.childNodes.get(charComponent);
currentStemBuilder.push(charComponent);
if (navigatorNode.isRootTerminus) {
shortestRootFound = currentStemBuilder.join("");
break;
}
}
return shortestRootFound;
}
}
/**
* Replace Words
* Time Complexity: O(Sum(L_root) + Total_Sentence_Length)
* Space Complexity: O(Sum(L_root) + Total_Sentence_Length)
*/
var replaceWords = function (dictionaryCollection, inputPhrase) {
const prefixTree = new TrieStructure();
for (const rootEntry of dictionaryCollection) {
prefixTree.insertWord(rootEntry);
}
const tokenizedPhrase = inputPhrase.split(" ");
const finalOutputWords = [];
for (const phraseToken of tokenizedPhrase) {
const identifiedRoot = prefixTree.findShortestRoot(phraseToken);
if (identifiedRoot !== null) {
finalOutputWords.push(identifiedRoot);
} else {
finalOutputWords.push(phraseToken);
}
}
return finalOutputWords.join(" ");
};