LeetCode代码分析——38. Count and Say(

2018-05-15  本文已影响9人  JackpotDC

题目描述

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();
    }

}
上一篇下一篇

猜你喜欢

热点阅读