-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-128-tokenTransform-2.js
101 lines (88 loc) · 2.09 KB
/
structy-128-tokenTransform-2.js
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
96
97
98
99
100
101
// p: obj, str
// r: str
// const tokens = {
// '$LOCATION$': '$ANIMAL$ park',
// '$ANIMAL$': 'dog',
// }; i
// tokenTransform('Walk the $ANIMAL$ in the $LOCATION$!', tokens);
// j
// // -> 'Walk the dog in the dog park!'
// dp 2 pointers W memo
const tokenTransform = (s, tokens) => {
let i = 0,
j = 1;
let result = "";
while (i < s.length) {
if (s[i] === "$") {
if (s[j] === "$") {
const key = s.slice(i, j + 1);
const value = tokenTransform(tokens[key], tokens);
tokens[key] = value; // memo, replace current value = 'the-end'-value
result += tokens[key];
i = j + 1;
j = i + 1;
} else {
j++;
}
} else {
result += s[i];
i++;
j++;
}
}
return result;
};
// // WO memo
// const tokenTransform = (s, tokens) => {
// let i = 0,
// j = 1;
// let result = "";
// while (i < s.length) {
// // console.log(s);
// if (s[i] === "$") {
// if (s[j] === "$") {
// const newS = tokens[s.slice(i, j + 1)];
// // console.log(newS);
// result += tokenTransform(newS, tokens);
// console.log(result);
// i = j + 1;
// j = i + 1;
// } else {
// j++;
// }
// } else {
// result += s[i];
// i++;
// j++;
// }
// }
// return result;
// };
// brute force
// const tokenTransform = (s, tokens) => {
// let i = 0,
// j = 1;
// // let result = '';
// while (i < s.length) {
// if (s[i] === "$") {
// if (s[j] === "$") {
// s = s.slice(0, i) + tokens[s.slice(i, j + 1)] + s.slice(j + 1);
// j = i + 1;
// } else {
// j++;
// }
// } else {
// // result += c;
// i++;
// j++;
// }
// }
// return s;
// };
const tokens = {
$LOCATION$: "$ANIMAL$ park",
$ANIMAL$: "dog",
};
// console.log(tokenTransform("Walk the!", tokens));
console.log(tokenTransform("Walk the $ANIMAL$ in the $LOCATION$!", tokens));
// -> 'Walk the dog in the dog park!'