LeetCode 38:Count and Say

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

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

Given an integer n, generate the nth sequence.

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

"数和说"序列的开头如下:

1, 11, 21, 1211, 111221, ...

1 读作"一个1" 或者11 (1个1)

11 读作"两个1" 或者21 (2个1)

21 读作"一个2,然后是一个1" 或者1211 (1个2,1个1)

给定一个整数n,返回第n个"数和说"序列

注意:返回的整数序列应当作用一个字符串表示


第一次写出一次通过的代码。。。虽然是很简单的题目但还是很高兴←_←思路就是从左往右读,读到不一样的就记录前面读到的个数和数字,然后接着读。。。

class Solution {
public:
    string countAndSay(int n) {
        string temp="1";
        for(int i=1;i<n;i++)
        {
            string temp1;
            int num=temp[0]-'0';
            int count=0;
            for(int j=0;j<temp.length();j++)
            {
                if(temp[j]-'0'==num)
                    count++;
                else
                {
                    temp1.append(to_string(count));
                    temp1.push_back(num+'0');
                    num=temp[j]-'0';
                    count=1;
                }
            }
            temp1.append(to_string(count));
            temp1.push_back(num+'0');
            temp=temp1;
        }
        return temp;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值