LeetCode 38. Cound and Say

题目来源:https://leetcode.com/problems/count-and-say/

问题描述

38. Count and Say

Easy

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1

2.     11

3.     21

4.     1211

5.     111221

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

 

Example 1:

Input: 1

Output: "1"

Example 2:

Input: 4

Output: "1211"

------------------------------------------------------------

题意

给定一个由数字组成的字符串,按照数字的读法写出写一个字符串。

------------------------------------------------------------

思路

用两个指针pre和cur遍历字符串分别保存之前的字符和当前字符,再用cnt统计截止到cur,pre字符出现的次数。特别注意字符串首端和字符串尾端的处理。

------------------------------------------------------------

代码

class Solution {
    public String countAndSay(int n) {
        if (n == 0)
        {
            return "";
        }
        if (n == 1)
        {
            return "1";
        }
        StringBuilder sb = new StringBuilder("1");
        int i = 1, len = 0, j = 0, cnt = 0;
        char cur = 0, pre = 0;
        for (i=2; i<=n; i++)
        {
            len = sb.length();
            cnt = 0;
            pre = 0;
            cur = 0;
            StringBuilder sb1 = new StringBuilder();
            for (j=0; j<len; j++)
            {
                cur = sb.charAt(j);
                if (pre == 0)
                {
                    pre = cur;
                }
                else if (cur == pre)
                {
                    cnt++;
                }
                else
                {
                    char chcnt = (char)(cnt+'1');
                    sb1.append(chcnt);
                    sb1.append(pre);
                    cnt = 0;
                    pre = cur;
                }
            }
            char chcnt = (char)(cnt+'1');
            sb1.append(chcnt);
            sb1.append(cur);
            sb = sb1;
        }
        return sb.toString();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值