lintcode 报数(Count and Say) (Java)

17 篇文章 0 订阅

题目

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, …
1 读作 “one 1” -> 11.
11 读作 “two 1s” -> 21.
21 读作 “one 2, then one 1” -> 1211.
给定一个整数 n, 返回 第 n 个顺序。
注意事项
整数的顺序将表示为一个字符串。

样例

给定 n = 5, 返回 “111221”.

分析

想得到下一个数是多少,首先要循环当前数,在循环的同时对相同的数进行计数,当碰到两个数不同时进行字符串拼接(数目+当前数),计数置为1。

代码

public class Solution {
    /**
     * @param n the nth
     * @return the nth sequence
     */
  public String countAndSay(int n) {
        // Write your code here

        String s = "1";
        int i = 1;
        while (i < n){
        //进行
            s = count(s);
            i ++;
        }
        return s;
    }

    public String count(String a){

        char[] chars = a.toCharArray();
        //计数
        int num = 1;

        StringBuffer buffer = new StringBuffer();

        for(int i = 1; i < chars.length ; i++){

            if (chars[i-1] == chars[i]){
                num++;
            }else {
                buffer.append(num + String.valueOf(chars[i-1]));
                num = 1;
            }
        }
        //拼接最后一个
        buffer.append(num + String.valueOf(chars[chars.length - 1]));
        return  buffer.toString();
    }
}

题目地址:http://www.lintcode.com/zh-cn/problem/count-and-say/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值