• leetcode-数数并说


     数数并说
     
     

    报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

    1.     1
    2.     11
    3.     21
    4.     1211
    5.     111221
    

    1 被读作  "one 1"  ("一个一") , 即 11
    11 被读作 "two 1s" ("两个一"), 即 21
    21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211

    给定一个正整数 n ,输出报数序列的第 n 项。

    注意:整数顺序将表示为一个字符串。

    示例 1:

    输入: 1
    输出: "1"
    

    示例 2:

    输入: 4
    输出: "1211"


    要获得下一个字符串,需要对上一个字符串的每一个数字进行处理,如果有相同的数字要合并,比如111,不同的单个数字比如12,则先对1处理,再对2处理,且得到的结果都是两个为一组。
    class Solution {
        public String countAndSay(int n) {
            String res="1";
            if(n==1)return res;
            String tmp="";
            while(n>1){
                char tmpchr;
                int index=0;    //每次遍历res的索引
                while(index<res.length()){    //遍历res
                    int count=0;    //有几个1、几个2、几个3的标记
                    tmpchr=res.charAt(index);  
                    while(index<res.length()&&res.charAt(index)==tmpchr){   //前一个数字与后一个数字的比较
                        count++;
                        index++;
                    }
                    tmp=tmp+count+tmpchr;
                }    
                 res=tmp.toString();   //到了最后再转移字符串
                    tmp="";   //用完清空临时字符串
              n--;  
            }
          return res;      
    }
        }
  • 相关阅读:
    0055. Jump Game (M)
    0957. Prison Cells After N Days (M)
    Java
    Java
    Java桌面应用程序打包
    JavaGUI练习
    Java贪吃蛇小游戏
    Java GUI编程
    Java异常处理机制
    抽象类与接口
  • 原文地址:https://www.cnblogs.com/patatoforsyj/p/9458423.html
Copyright © 2020-2023  润新知