Leetcode #38. Count and Say 数数报数 解题报告

1 解题思想

这道题就是按照每一位读一下数字,然手输出
比如123就是1个1,1个2,一个3,输出111213嗯,也就是先输出个数,然后输出元素

做法就是扫描,统计了,统计连续相同的数字,毕竟Easy难度~~

2 原题

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.

Subscribe to see which companies asked this question

3 AC解

public class Solution {
    /** * 这道题就只能不断的统计然后输出了。。其他我不知道有啥数学规律了 * */
    public String countAndSay(int n) {
        String start="1";
        int num=0,count=0,i=0;
        char tmp;
        while(n-->1){
            char chars[]=start.toCharArray();
            StringBuilder sb=new StringBuilder();
            i=0;
            while(i<chars.length){
                count=0;
                tmp=chars[i];
                while(i<chars.length && chars[i]==tmp){
                    count++;
                    i++;
                }
                sb.append(count+""+tmp);  
            }
            start=sb.toString();
        }
        return start;

    }
}

你可能感兴趣的:(LeetCode)