LeetCode Count and Say

原题链接在这里:https://leetcode.com/problems/count-and-say/

当前的读音用来做数列的下一个"1" 读成1个1,写成"11"用来作为下一个。

从i = 2开始一直到n作为外层loop, i是第 ith 个结果。

进入循环后,新生成count = 1, index = 1, 然后进入内层loop, 用index 从第二位走res, 现字符等同于前字符就count++, 不同字符就先append count, 然后 append 前字符,然后count归为1. 走完内层loop, 再把最后一段的count, 字符加到StringBuilder中。

Note:  count, StringBuikder,index 都需要在外层循环归回原数。

AC Java:

public class Solution {
    public String countAndSay(int n) {
        if(n<=0){
            return "";
        }
        if(n==1){
            return "1";
        }
        String res = "1";
        for(int i = 2; i<=n; i++){
            int count = 1;
            StringBuilder sb = new StringBuilder();
            int index = 1;
            for( index = 1; index<res.length(); index++){
                if(res.charAt(index) == res.charAt(index-1)){
                    count++;
                }else{
                    sb.append(count);
                    sb.append(res.charAt(index-1));
                    count = 1;
                }
            }
            sb.append(count);
            sb.append(res.charAt(index-1));
            res = sb.toString();
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值