##题目:
The count-and-say sequence is the sequence of integers with the first five terms as following:
-
1 -
11 -
21 -
1211 -
111221
1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
var countAndSay = function(n) {
let res = '1';
if (n === 1) return '1';
for (let i = 1; i <= n; i++) {
res = round(res);
}
return res;
};
function round(nowString) {
let res = '';
let nowNumber = nowString[0];
let nowNumberCount = 0;
for (let i = 0; i < nowString.length; i++) {
if (nowString[i] === nowNumber) {
nowNumberCount++;
} else {
res = `${res}${nowNumberCount}${nowNumber}`;
nowNumber = nowString[i];
nowNumberCount = 1;
}
}
res = `${res}${nowNumberCount}${nowNumber}`;
return res;
}
这个题目是属于顺推类型的,下一层的结果需要根据上一层来计算,所以理解题目的意思其实很简单:
1.封装一个round方法,表示每回合从上一层得到当前层的结果; 2.round方法遍历上一层字符串,如果当前字符跟上一个字符相同则数量相加,否则加入结果字符串当中,然后重置当前的字符和字符数量。