leetcode 第38题:Count and Say

题意理解

在discuss里面发现了一个解释比较清楚:

careercup 上有个相同的问题 , 对于Count and Say 问题是这么描述的。
http://www.careercup.com/question?id=4425679

“Count and Say problem” Write a code to do following:
n String to print
0 1
1 1 1
2 2 1
3 1 2 1 1

Base case: n = 0 print “1”
for n = 1, look at previous string and write number of times a digit is seen and the digit itself. In this case,
digit 1 is seen 1 time in a row… so print “1 1”
for n = 2, digit 1 is seen two times in a row, so print “2 1”
for n = 3, digit 2 is seen 1 time and then digit 1 is seen 1 so print “1 2 1 1”
for n = 4 you will print “1 1 1 2 2 1”
Consider the numbers as integers for simplicity. e.g. if previous string is “10 1” then the next will be “1 10 1 1” and the next one will be “1 1 1 10 2 1”

意思就是观察前一个字符串,数一个数字出现的次数并说出来
n = 0 打印1
n = 1 观察n = 0 有一个1,所以打印“1 1”
n = 2 观察n = 1 有两个1,所以打印“2 1”
n = 3 观察n = 2 有一个2一个1,所以打印“1 2 1 1”
以此类推


my code use recursion:

public static String countAndSay(int n) {
    List<String> list = new ArrayList<String>();
    countAndSay(list, "1", n, 1);
    return list.get(0);
}
public static void countAndSay(List<String> list, String string1, int n, int num) {
    if (num == n) {
        list.add(string1);
        return;
    }
    String string2 = "";
    char[] chars = string1.toCharArray();
    int count = 1;
    for (int i = 0; i < chars.length; i++) {
        if (i == chars.length - 1 ||chars[i] != chars[i + 1]) {
            string2 = string2 + count + chars[i];
            count = 1;
        }
        else {
            count++;
            continue;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值