• count-and-say


    /**
    * The count-and-say sequence is the sequence of integers beginning as follows:
    * 1, 11, 21, 1211, 111221, ...
    * 1is read off as"one 1"or11.
    * 11is read off as"two 1 s"or21.
    * 21is read off as"one 2, thenone 1"or1211.
    * Given an integer n, generate the n th sequence.
    * Note: The sequence of integers will be represented as a string.
    *
    * 题意是n=1时输出字符串1;
    * n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
    * n=3时,由于上次字符是11,有2个1,所以输出21;
    * n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
    * n=5时,由于上次字符串是1211,有1个1、1个2和2个1,所以输出111221.
    */
    这道题真的需要好好理解一下子,用翻译来看的话,有点难理解,后来还是去百度相关博客才真正的理解它的意思。
    /**
     * The count-and-say sequence is the sequence of integers beginning as follows:
     * 1, 11, 21, 1211, 111221, ...
     * 1is read off as"one 1"or11.
     * 11is read off as"two 1 s"or21.
     * 21is read off as"one 2, thenone 1"or1211.
     * Given an integer n, generate the n th sequence.
     * Note: The sequence of integers will be represented as a string.
     *
     * 题意是n=1时输出字符串1;
     * n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
     * n=3时,由于上次字符是11,有2个1,所以输出21;
     * n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
     * n=5时,由于上次字符串是1211,有1个1、1个2和2个1,所以输出111221.
     */
    
    public class Main35 {
        public static void main(String[] args){
            System.out.println(Main35.countAndSay(2));
        }
    
        public static String countAndSay(int n) {
            if (n==1) {
                return "1";
            }
            String str = countAndSay(n-1)+"*";
            char[] ch = str.toCharArray();
            int count = 1;
            String s = "";
            for (int i=0;i<ch.length-1;i++){
                if (ch[i] == ch[i+1]) {
                    count++;
                }else{
                    s = s + count + ch[i];
                    count = 1;
                }
            }
            return s;
        }
    }
    

      

  • 相关阅读:
    一键编译go文件命令.bat
    安装go语言,配置环境及IDE,只需3步
    Mysql show Status常用参数详解
    LFS:kernel panic VFS: Unable to mount root fs
    LFS: Interface eth0 doesn't exist
    转:Xshell显示找不到匹配的outgoing encryption算法怎么办
    NTP-ntpdate:no server suitable for synchronization found
    linux/module.h: No such file or directory 内核模块编译过程
    ASCII码表完整版
    [Firmware Warn]: GHES: Failed to read error status block address for hardware error source
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11313642.html
Copyright © 2020-2023  润新知