LeetCode 38. 报数 (java)

题目:

https://leetcode-cn.com/problems/count-and-say/

题意:

 

     题意不太好理解,它的规律就是每一个都在解释它上一个数的组成,比如第三个是21,第四个是1211,表示第三个又一个二,一个一组成。

     解题的时候利用递归逐层的解决就行啦。

 1 class Solution {
 2     public String countAndSay(int n) {
 3         if(n==1)
 4             return "1";
 5         String str=countAndSay(n-1)+"*";          //这里一定要有*,作为数组的结束,方便下面循环判断结束。
 6         char c[]=str.toCharArray();
 7         int count=1;
 8         String s="";
 9         for(int i=0;i<c.length-1;i++){
10             if(c[i]==c[i+1])                      //*在这里发挥作用,便于判断最后一个字符是否与*相等,如果没有*结尾,会发生错误。
11                 count++;
12             else{
13                 s=s+count+c[i];
14                 count=1;
15             }
16         }
17         return s;
18     }
19 }
原文地址:https://www.cnblogs.com/y1040511302/p/11279383.html