leetcode 38. 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.

理解题意:
首先 如果把每一位取出来看的话 就是看这一位和下一位一不一样 一样就计算器加一 不一样就计数器清零
所以只用两个变量 一个count 一个value应该就够了

11213
1:                   value:1    count:1
11:                   value:1    count:2    
112:                  value:2    count:1    输出21
1121:                 value:1    count:1    输出21
11213:                value:3    count:1    输出11                                                                                                                    输出13
public String countAndSay(int n) {
        String[] strings = new String[n];
        for(int i = 0;i < n;i++){
            if(i == 0) strings[i] = "1";
            else strings[i] = countAndSayForString(strings[i-1]);
        }
        return strings[n-1];
    }

    public String countAndSayForString(String s) {
        StringBuffer result = new StringBuffer();
        int count = 0;
        char value = ' ';
        for(char c:s.toCharArray()){
            if(c != value){
                if(value != ' '){
                    result.append(count + "" + value);
                } 
                value = c;
                count = 1;
            }
            else {
                count ++;
            }
        }
        result.append(count + "" + value);
        return result.toString();
    }

这道题虽然简单 但是刚开始的时候题意理解错了
n=1 返回1
n=2 返回11
n=3 返回21
n=4 返回1211
n=5 返回111221
这才是题目要的String countAndSay(int n) 函数
之前理解成是 n=5 返回15了 看懂题目很重要!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值