-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
46 lines (40 loc) · 1.18 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
function countAndSay(n: number): string {
const cached = cache.get(n);
if (cached) {
return cached;
}
const sb: string[] = [];
if (n === 1) {
sb.push("1");
} else {
let prev = countAndSay(n - 1);
if (prev.length === 1) {
sb.push("" + "1" + prev);
} else {
while (prev.length) {
const start = prev[0];
if (prev[1] && start !== prev[1]) {
sb.push("" + "1" + start);
prev = prev.slice(1);
} else {
const index = Array.prototype.findIndex.call(
prev,
(v) => v !== start,
);
if (index >= 0) {
sb.push("" + index + start);
prev = prev.slice(index);
} else {
sb.push("" + prev.length + start);
prev = "";
}
}
}
}
}
const res = sb.join("");
cache.set(n, res);
return res;
}
const cache = new Map<number, string>();
export default countAndSay;