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+"";
    };
  • 相关阅读:
    感知机预测NBA总冠军
    java 一维数组
    2020-11-25
    2020-11-24学习日记
    Java语言概述
    人脸情绪识别系统---测试心得
    结对编程,问题不大
    结对编程之队友代码赏析
    项目测试心得——基于微信的图书销售小程序
    数据库设计心得
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10415297.html
Copyright © 2011-2022 走看看