• 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 }
  • 相关阅读:
    QQ空间留言的JS
    Session超时问题(AOP 过滤器)
    IFrame实现的无刷新(仿ajax效果)...
    NPOI帮助类(Excel转DataTable、DataTable转Excel)
    SignalR with ASP.NET MVC5 可用于倒计时同步
    我(webabcd)的文章索引
    WorkFlow4.0--入门到精通系列-专题索引
    Android利用Fiddler进行网络数据抓包
    IIS给网站地址配置成HTTPS的
    SQL SERVER 2005 获取表的所有索引信息以及删除和新建语句
  • 原文地址:https://www.cnblogs.com/ncznx/p/9257419.html
Copyright © 2020-2023  润新知