zoukankan      html  css  js  c++  java
  • LeetCode 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, 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"

    题意:

    当n=1,str="1"
    当n=2,因为当n=1时,str="1",里面有一个“1”,所以此时的str="11"
    当n=3,因为当n=2时,str="11",里面有两个“1”,所以此时的str="21"
    当n=4,因为当n=3时,str="21",里面有一个"2",一个“1”,所以此时的str="1211"
    当n=5,因为当n=4时,str="1211",里面是:先一个"1",再一个"2",最后两个“1”,所以此时的str="111221"
    即:第i+1个字符串是第i个字符串的读法。

    思路:直接模拟解决,代码如下:

    String s = "1";
            int count = 1, j;
            StringBuilder str = new StringBuilder();
            for(int i = 2; i <= n; i++){
                for(j = 0; j < s.length(); j++){
                    while(j + 1 < s.length() && s.charAt(j) == s.charAt(j + 1)){
                        j++;
                        count++;
                    }
                    str.append(Integer.toString(count) + s.charAt(j));
                    count = 1;
                 }
                s = str.toString();
                str.delete(0, str.length());
            }
             return s;
        }
  • 相关阅读:
    考试剩余时间倒计时
    MVC URL处理
    .net core 使用DES加密字符串
    JS时间处理,获取天时分秒。以及浏览器出现的不兼容问题
    NLog使用说明
    开发工具集
    js模拟下载
    DataTable导出Excel
    Ajax提交打开新窗口,浏览器拦截处理;以及跨域问题
    jquery_DOM笔记
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7853496.html
Copyright © 2011-2022 走看看