zoukankan      html  css  js  c++  java
  • Count and Say

    描述
    The count-and-say sequence is the sequence of integers beginning as follows:
    1, 11, 21, 1211, 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 sequence.
    Note: �e sequence of integers will be represented as a string.
    分析

    计数和说序列是从如下开始的整数序列:
    1, 11, 21,1211, 111221,…
    1被读出为“一个1”或11。
    11被读出为“两个1s”或21。
    21被读出为“一个2,然后一个1”或1211。
    给定整数n,生成第n序列。
    注意:整数序列将被表示为字符串。

    解释一下就是,输入n,那么我就打出第n行的字符串。

    怎么确定第n行字符串呢?他的这个是有规律的。

     n = 1时,打印一个1。

     n = 2时,看n=1那一行,念:1个1,所以打印:11。

     n = 3时,看n=2那一行,念:2个1,所以打印:21。

     n = 4时,看n=3那一行,念:一个2一个1,所以打印:1211。

    以此类推。(注意这里n是从1开始的)

    代码

    参考https://www.cnblogs.com/springfor/p/3889221.html

     1 public class CountAndSay {
     2 
     3     public static void main(String[] args) {
     4         // TODO Auto-generated method stub
     5         System.out.println(countAndsay(5));
     6     }
     7 
     8     public static String countAndsay(int n) {
     9         if (n <= 0)
    10             return "";
    11         String curRes = "1";
    12         int start = 1;
    13         while (start < n) {
    14             StringBuffer res = new StringBuffer();
    15             int count = 1;
    16             for (int j = 1; j < curRes.length(); j++) {
    17                 if (curRes.charAt(j) == curRes.charAt(j - 1)) {
    18                     count++;
    19 
    20                 } else {
    21                     res.append(count);
    22                     res.append(curRes.charAt(j - 1));
    23                     count = 1;
    24                 }
    25             }
    26             res.append(count);
    27             res.append(curRes.charAt(curRes.length() - 1));
    28             curRes = res.toString();
    29             start++;
    30         }
    31         return curRes;
    32     }
    33 }
  • 相关阅读:
    函数的有用信息,装饰器 day12
    函数名、闭包、装饰器 day11
    函数的动态参数与命名空间 day10
    函数 day9
    集合 day8
    文件操作 day8
    基础数据类型补充,及capy daty7
    day7 回顾
    编码补充 daty 6
    字典的增删改查 daty 5
  • 原文地址:https://www.cnblogs.com/ncznx/p/9257419.html
Copyright © 2011-2022 走看看