38 Count and Say

题目链接:https://leetcode.com/problems/count-and-say/

题目:

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.

解题思路:
先来说下题目的要求,一开始没理解,导致思路完全错误。
题目要求我们按规律写出数字。
1 初始数字
11 表示上一个数字是1个数字1
21 表示上一个数字是21
1211 表示上一个数字是1211
111221 表示上一个数字是1112以及21

也就是说,当前轮的每一个数字都是根据上一个数字得出的。题目要求我们返回按上述规律得出的第 n 个数字。
因此为了得出第 n 个数字,必须求第 n - 1 个数字。
具体来说,我们把上一轮的数字都转成 String 类型。从左到右比较相邻字符是否相等
若相等,则做累加,得到当前字符的个数。
若不相等,则把上一轮的字符个数以及字符本身附加到 StringBuilder 变量中。
对于21来说,字符 2 和字符 1不相等,字符2 的个数为 1。则在 StringBuilder 变量中附加字符个数 1 和字符本身 2,形成 21。同理,字符 1 形成 11。组合两者得到 1121。

写完后例行看了看 Code Ganker 的解题思路,很开心自己的思路和他的几乎一致。不过人家说了,这一般是考查算法的第一道题,也就是水题,要力求一次通过,bug free !
参考链接:http://blog.csdn.net/linhuanmars/article/details/20679963

public class Solution {
    public String countAndSay(int n) {
        if(n == 1)
            return "1";
        if(n == 2)
            return "11";
        String num = "11";
        for(int i = 2; i < n; i ++) {
            StringBuilder sb = new StringBuilder();
            int count = 1;
            for(int j = 0; j < num.length() - 1; j ++) {
                if(num.charAt(j) == num.charAt(j + 1))
                    count ++;
                else {
                    sb.append(count);
                    sb.append(num.charAt(j));
                    count  = 1;
                }
            }
            if(count != 1) {
                sb.append(count);
                sb.append(num.charAt(num.length() - 1));
            } else {
                sb.append(1);
                sb.append(num.charAt(num.length() - 1));
            }
            num = sb.toString();
        }
        return num;
    }
}
18 / 18 test cases passed.
Status: Accepted
Runtime: 240 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值