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: 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);
        }
    }
  • 相关阅读:
    HTML if条件注释解读
    Springboot整合logback日志系统
    Springboot @Valid 参数校验
    JDK1.8 版的if else
    Android获取手机定位坐标
    CentOS8安装JDK
    Vue全局配置文件
    git学习
    百度前端面试题—基础
    前端知识网络
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4268940.html
Copyright © 2011-2022 走看看