今天开始刷leetcode,一天至少刷一道,然后每天要写笔记。。这是一道easy的题,但貌似太久没有刷题,都木有做出来,题目刚开始都理解错了。
The count-and-say sequence is the sequence of integers beginning as follows: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, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
大体意思:输入n,给出对应的第n个字符串。比如,当n=1,输出:1;n=2,输出:11;n=3,输出:21; n=4,输出:1211;......
另一方面,由题意可知,每一个数字的由来都是由它的上一个递归而来的,并且是每个连续相同的数字有几个下一个数字对应的就是啥。
对应的javascript程序
/* @param {number} n
@return {string} */
var countAndSay = function(n) {
if(n == 1){
return '1';
}
var str = countAndSay(n-1) + '*';
var count = 1;
var s = '';
for(var i = 0; i < str.length -1; i++){
if(str[i] == str[i+1]){
count++;
}else{
s = s + count + str[i];
count = 1;
}
}
return s;
}