알고리즘 공부
38. Count and Say
Sense.J
2020. 8. 24. 23:07
https://leetcode.com/problems/count-and-say/
Count and Say - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/**
* @param {number} n
* @return {string}
*/
const hash = {};
hash[0] = '';
hash[1] = '1';
hash[2] = '11';
hash[3] = '21';
hash[4] = '1211';
hash[5] = '111221';
const say = function(p_num)
{
const l_number = p_num.toString();
var res = "";
var cnt = 1;
var before = l_number.charAt(0);
var elem = '';
for( var i=1; i<l_number.length; ++i )
{
elem = l_number.charAt(i);
if( elem == before )
++cnt;
else
{
res += cnt + '' + before;
before = elem;
cnt = 1;
}
}
res += cnt.toString() + before.toString();
return res;
}
var countAndSay = function(n) {
const find = function(p_num)
{
return hash[p_num] ? hash[p_num]:( hash[p_num] = say( find(Number(p_num)-1) ) );
}
return find(n);
};