• 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;
        }
    }
    

      

  • 相关阅读:
    leetcode-23-DynamicProgramming-1
    perl-basic-数组操作
    R-data.table
    perl-basic-分支&循环
    neo4j3.0多数库切换
    Neo4j下载与使用
    python中导入模块的注意点
    python 一个.py文件如何调用另一个.py文件中的类和函数
    理解Python中的类对象、实例对象、属性、方法
    flowable+tomcat部署flowable项目,在线画流程图
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11313642.html
Copyright © 2020-2023  润新知