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+"";
    };
  • 相关阅读:
    管程|| 同步与互斥的实现策略
    sqlserver 用户定义表类型
    C# Post Get 方式发送请求
    linux centos Supervisor守护.netcore进程安装配置
    linux cenos开放端口
    SqlServer DbHelper
    C# 执行js
    sql 多行、一行 互转
    sql 删除完全表中完全重复的数据保留一条
    sql 行列互转
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10415297.html
Copyright © 2011-2022 走看看