• 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: The sequence of integers will be represented as a string.

     刚开始题目理解错了,以为求n的转换后的数字,后来仔细一看(1,11,21,1211,111221,。。。)是一个序列,后一个数是前一个的count-and-say表示,题目要求这个序列的第n个数。代码如下:

    public class Solution {
        
        //当前数字为num求出下一个数字
        public String getNextNum(String num){
            String re = "";
            char[] array = num.toCharArray();
            int size = array.length;
            int count = 0;
            char temp = array[0];
            for(int i=0;i<size;i++){
                if(array[i] == temp){
                    count++;
                }
                else{
                    re = re+count+temp;
                    temp = array[i];
                    count = 1;
                }
                //存在1,11的特殊情况,即无法进入上面else内
                if(i == size-1){
                    re = re+count+temp;
                }
            }
            return re;
        }
        
        public String countAndSay(int n) {
            ArrayList<String> list = new ArrayList<String>();//顺序存放count-and-say序列
            list.add("1");
            for(int i=1;i<n;i++){
                String next = getNextNum(list.get(i-1));
                list.add(next);
            }
            return list.get(n-1);
        }
    }
  • 相关阅读:
    防抖函数
    video.js汉化
    vscode 设置
    webpack配置
    寄生组合继承
    数组排序
    操作节点的方法
    vscde软件
    vue目录详解
    前端
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4268940.html
Copyright © 2020-2023  润新知