LeetCode代码分析——38. Count and Say(简单的计数)

题目描述

The count-and-say sequence is the sequence of integers with the first five terms as following:
计数并且说出来

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

1 is read off as "one 1" or 11. 1读出来就是一个1,即11
11 is read off as "two 1s" or 21. 11读出来就是两个1,即21
21 is read off as "one 2, then one 1" or 1211. 21读出来就是一个2,一个1,读出来就是1211
Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"

思路分析

这个题其实没啥难度,主要是要读懂题目,我刚开始看了半天都没读懂。。。明白题目意思以后,其实就是简单的在遍历中计数了,用一个cur变量来记录当前计数的数字,再用一个变量cnt记录当前的计数值,如果遇到字符改变了(例如1211,遇到2了),则将上次的数字和计数值添加到结果中,然后再继续。

代码实现

public class Solution {

    /**
     * 18 / 18 test cases passed.
     *  Status: Accepted
     *  Runtime: 6 ms
     *
     * @param n
     * @return
     */
    public String countAndSay(int n) {
        StringBuilder say = new StringBuilder("1");
        StringBuilder nextSay = new StringBuilder();
        for (int i = 0; i < n - 1; i++) {
            // 这里为了方便区分是刚开始统计还是,中间的变化,
            // 所以刚开始cur赋值为一个默认的'0',
            // 这样遇到刚开始遍历和遍历中数字变化的情况可以统一处理
            char cur = '0';
            int cnt = 0;
            for (int j = 0; j < say.length(); j++) {
                if (say.charAt(j) != cur) {
                    if (cur != '0') {
                        nextSay.append((char) ('0' + cnt));
                        nextSay.append(cur);
                    }
                    cur = say.charAt(j);
                    cnt = 1;
                } else {
                    cnt++;
                }
            }
            nextSay.append((char) ('0' + cnt));
            nextSay.append(cur);
            say = nextSay;
            nextSay = new StringBuilder();
        }
        return say.toString();
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,505评论 0 13
  • Introduction What is Bowtie 2? Bowtie 2 is an ultrafast a...
    wzz阅读 5,816评论 0 5
  • 早晨三点半就从家出发,赶往机场。孩子们兴致勃勃地来到机场。 在飞机上。 座了三个小时飞机,终于到达呼伦贝尔大草原机...
    哪凉快去哪呆着去阅读 224评论 0 0
  • 2017.11.7 当班主任通知星期二要期中考试的时候我开始替孩子激动,但是孩子一点也不紧张,也...
    0向幸福出发0阅读 179评论 0 1
  • 今年,国家列出一张电信不良经营企业名单,全名叫《2019年三季度21家违规企业被纳入电信业务经营不良名单》,然...
    软件奋兴阅读 192评论 0 1