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;
        }
  • 相关阅读:
    JOI2017FinalC JOIOI 王国
    JOISC2017C 手持ち花火
    P4336 [SHOI2016]黑暗前的幻想乡
    SP104 HIGH
    P3160 [CQOI2012]局部极小值
    P4965 薇尔莉特的打字机
    【BZOJ4361】isn
    P3506 [POI2010]MOT-Monotonicity 2
    P3214 [HNOI2011]卡农
    P3704 [SDOI2017]数字表格
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7853496.html
Copyright © 2011-2022 走看看