zoukankan      html  css  js  c++  java
  • 38. Count and Say(js)

    38. Count and Say

    The count-and-say sequence is the sequence of integers with the first five terms as following:

    1.     1
    2.     11
    3.     21
    4.     1211
    5.     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+"";
    };
  • 相关阅读:
    抽象类存在的意义
    抽象类的特征
    抽象类的使用
    抽象类的概述
    引用类型作为方法参数和返回值
    继承的特点
    目前Java水平以及理解自我反思---01
    继承后- 构造器的特点
    指针函数
    C数组灵活多变的访问形式
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10415297.html
Copyright © 2011-2022 走看看