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)、1

    2)、11,表示1)有1个1,组合起来就是11。

    3)、21,表示2)有2个1,组合起来就是21。

    4)、1211,表示3)有1个2,2个1,组合起来就是1211。

    5)、111221,表示4)有1个1,1个2,2个1,组合起来就是111221。

    6)、312211,表示5)有3个1,2个2,2个1,组合起来就是312211。

    以此类推,求给定n行的输出结果。

    思路:

    "1  1  1  2  2  1"  

             j                                                 查看 j 对应值 == j-1 对应值, count更新为2

                    j                                          查看 j 对应值 == j-1 对应值, count更新为3

                           j                                   查看 j 对应值 != j-1 对应值,打包前面(count: 3) + previous.charAt(j-1) = '3' + '1' =  '31', count初始化为1

                                    j                          查看 j 对应值 == j-1 对应值, count更新为2

                                           j                   查看 j 对应值 != j-1 对应值,打包前面(count: 2) + previous.charAt(j-1) = '2' + '2' =  '22', count初始化为1

    代码:

     1 class Solution {
     2     public String countAndSay(int n) {
     3         String pre = "1";
     4         for(int i = 2; i<=n; i++){
     5             StringBuilder sb = new StringBuilder();
     6             int count = 1;
     7             for(int j =1; j< pre.length() ; j++){
     8                 if(pre.charAt(j) == pre. charAt(j-1)){
     9                     count++;
    10                 }else{
    11                     sb.append(count+"");
    12                     sb.append(pre.charAt(j-1));
    13                     count = 1;
    14                 }
    15             }
    16             sb.append(count+"");
    17             sb.append(pre.charAt(pre.length()-1));
    18             pre = sb.toString();
    19              
    20         }
    21        return pre; 
    22     }
    23 }
  • 相关阅读:
    英黑客侵入Zynga系统窃得价值1200万美元筹码 狼人:
    瑞星发布2010企业安全报告 九成国内企业曾被入侵 狼人:
    赛门铁克大中国区总裁吴锡源:云安全是一项系统工程 狼人:
    频遭攻击 索尼无奈关闭多国网站 狼人:
    Pwn2Own黑客大赛首日:Safari、IE8被攻破 狼人:
    疯子的研究:瘫痪整个互联网绝非天方夜谭 狼人:
    Google收购安全分析软件厂商Zynamics 狼人:
    RSA大会:黑客正在觊觎个人用户而非网络 狼人:
    从索尼泄密看云计算安全 狼人:
    RSA公布被攻击内幕:钓鱼邮件惹祸 狼人:
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9142935.html
Copyright © 2011-2022 走看看