- 38. Count and Say
- 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.
- Example 1:
- Input: 1
- Output: "1"
- Example 2:
- Input: 4
- Output: "1211"
题意: 第一项是 1 个 1, 所以第二项是 11, 第二项是 2 个 1, 所以第三项是 21,.... 以此类推
代码如下:
- /**
- * @param {number} n
- * @return {string}
- */
- var countAndSay = function(n) {
- var s='1';
- for(var i=1;i<n;i++){
- s=getStr(s);
- // console.log(s)
- }
- // console.log(s);
- return s;
- };
- var getStr=function(s){
- var curr=s.charAt(0);
- var count=1;
- var res="";
- for(var i=1;i<s.length;i++){
- if(s.charAt(i)== curr){
- count++;
- }else{
- // 与前一个字符不相同, 立即将前面收集的字符存入 res
- res=res+count+curr;
- // 当前字符存入 curr
- curr=s.charAt(i);
- count=1;
- }
- }
- res=res+count+curr;
- return res+"";
- };
来源: http://www.bubuko.com/infodetail-2963450.html