Skip to content

Commit a2344c9

Browse files
committed
Count say
1 parent 116c633 commit a2344c9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

coding/leetcode/38-count-say.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const DEBUG = false;
2+
3+
var countAndSay = function(n) {
4+
let i = n - 1;
5+
n = "1";
6+
while(i--) {
7+
n = nextCS(n);
8+
}
9+
return n;
10+
};
11+
12+
function nextCS(n) {
13+
const runs = Array.from(n).reduce((R, char) => {
14+
let run = R.pop();
15+
16+
if ( run && (run.char !== char) ) {
17+
R.push(run);
18+
run = null;
19+
}
20+
21+
if ( ! run ) {
22+
run = {
23+
char,
24+
count: 0
25+
};
26+
}
27+
28+
run.count++;
29+
30+
R.push(run);
31+
32+
return R;
33+
}, []);
34+
DEBUG && console.log(runs);
35+
return runs.reduce((S, {char,count}) => S + `${count}${char}`, '');
36+
}
37+
38+
console.log(countAndSay(5));

0 commit comments

Comments
 (0)