LeetCode—count-and-say(计数并说出来)—java

138 篇文章 0 订阅
132 篇文章 0 订阅

题目描述

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integer n, generate the n th sequence.

Note: The sequence of integers will be represented as a string.

思路解析

  • 首先需要判断n的合法性
  • 然后需要计数,初始化第一个curStr为“1”,计数从1开始
  • 对上一个string进行遍历计数,如果计数完毕,就把count加入到新的字符串中,记得把count设置为1;
  • 遍历完毕前一个字符串后,记得把最后一个count和最后一个字符加入到下一个字符串,开始的位置增加1

代码

public class Solution {
    public String countAndSay(int n) {
        if(n<0)
            return "";
        String curRes = "1";
        int start =1,i;//注意i声明在外边哦
        while(start<n){
            StringBuilder res = new StringBuilder();
            int count =1;
            for(i=1;i<curRes.length();i++){
                if(curRes.charAt(i)==curRes.charAt(i-1)){//计数有多少个相同的字符
                    count++;
                }else{
                    res.append(count);//没有相等的了就要加入新的字符串中了
                    res.append(curRes.charAt(i-1));
                    count=1;
                }
            }
            res.append(count);
            res.append(curRes.charAt(i-1));
            curRes = res.toString();
            start++;
        }
        return curRes;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值