[leetcode] Count and Say

本文介绍了一种名为“计数并描述”的整数序列生成算法,该序列以1开始,随后每一项都是对前一项的描述。例如,1被描述为“one 1”即11;11被描述为“two 1s”即21。文章提供了使用Java实现的具体代码,并通过迭代的方式生成序列。

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 nth sequence.

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

https://oj.leetcode.com/problems/count-and-say/

思路:模拟题,一遍一遍推即可。

public class Solution {
    public String countAndSay(int n) {
        if (n <= 0)
            return null;
        StringBuilder sb = new StringBuilder();
        sb.append("1");
        for (int i = 0; i < n - 1; i++) {
            StringBuilder nsb = new StringBuilder();

            for (int j = 0; j < sb.length();) {
                char cur = sb.charAt(j);
                int cnt = 0;
                while (j<sb.length()&&sb.charAt(j) == cur) {
                    j++;
                    cnt++;
                }
                nsb.append((char)(cnt + '0'));
                nsb.append(cur);

            }

            sb = nsb;
        }
        return sb.toString();

    }

    public static void main(String[] args) {
        System.out.println(new Solution().countAndSay(1));
        System.out.println(new Solution().countAndSay(2));
        System.out.println(new Solution().countAndSay(3));
        System.out.println(new Solution().countAndSay(4));
        System.out.println(new Solution().countAndSay(5));
        System.out.println(new Solution().countAndSay(6));
    }

}

 

第二遍记录:

  用两个StringBuilder迭代。

 

 

转载于:https://www.cnblogs.com/jdflyfly/p/3810747.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值