-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38.count-and-say.js
More file actions
55 lines (46 loc) · 833 Bytes
/
Copy path38.count-and-say.js
File metadata and controls
55 lines (46 loc) · 833 Bytes
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
/*
* @lc app=leetcode id=38 lang=javascript
*
* [38] Count and Say
*/
/**
* @param {number} n
* @return {string}
*/
/*
Question
represent a number by a string
1=>1
2=>11
3=>21
4=>1211
5=>111221
Rule
*/
var countAndSay = function(n) {
var hash = {};
hash[1] = "1";
var hashPos;
for (var i = n; i >= 1; i--) {
if (hash[i]) hashPos = i;
}
var str = hash[hashPos];
for (var i = hashPos + 1; i <= n; i++) {
var _str = "";
var target = "";
var num = 0;
for (var j = 0, len = str.length; j < len; j++) {
if (target === "") (target = str[j]), (num = 1);
else if (str[j] === target) num++;
else {
_str += num + target;
target = str[j];
num = 1;
}
}
if (num) _str += num + target;
str = _str;
hash[i] = str;
}
return str;
};