今天開始刷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;
}