【LeetCode】#38报数(Count and Say)

【LeetCode】#38报数(Count and Say)

题目描述

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。

示例

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

Description

The count-and-say sequence is the sequence of integers.

Example

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

解法

class Solution {
    public static String countAndSay(int n) {
        if(n==1){
            return "1";
        }
        return findNum(1, n, "1");
    }
    
    public static String findNum(int t, int n, String s){
        String[] str = s.split("");
        StringBuilder sb = new StringBuilder();
        String string = str[0];
        int sum = 1;
        for(int i=0; i<str.length; i++){
        	// System.out.println("string="+string+", sum="+sum+", str["+i+"]="+str[i]);
            if(i>0 && str[i].equals(string)){
            	// System.out.println("sum++");
                sum++;
            }else if(!str[i].equals(string)){
                sb.append(sum+"");
                sb.append(string);
                string = str[i];
                sum = 1;
            }
        }
        
        sb.append(sum+"");
        sb.append(string);
        
        if(t+1==n){
            return sb.toString();
        }else{
        	// System.out.println("t!=n,进入下一次循环");
            return findNum(t+1, n, sb.toString());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84825526
今日推荐