【leetcode】38. Count and Say

本文介绍了一种特殊的整数序列——计数并说序列,并提供了C++实现代码。序列从1开始,后续每一项是对前一项的描述。例如,1被描述为“一个1”,即11;11被描述为“两个1”,即21。

一、题目描述

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 1s" 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个1所以第二数字是11,2个1所以第三个数字是21,1个2和1个1所以第四个数字是1211.... 按这种规律类推


思路:从第三个开始,从1~n-1,对每个数字计数。每次都与前一个进行比较,相同就计数+1,否则就先把前一个数的个数+值存入结果字符串中。


c++代码(20ms,1.11%)

class Solution {
public:
    string countAndSay(int n) {
        string s="11";
        if(n==1)
            return "1";
        if(n==2)
            return "11";
        
        for(int i=2;i<n;i++){
            string str="";
            for(int j=1;j<s.size();j++){
                int count=1;
                while(s[j] == s[j-1] && j<s.size()){
                    count++;
                    j++;
                }
                stringstream ss,cc;
                ss<<count;
                cc<<s[j-1];
                str+=ss.str()+cc.str();
                if(j==(s.size()-1) && s[j]!=s[j-1]){
                	int i=1;
                	stringstream mm,nn;
                	mm<<i;
                	nn<<s[j];
                	str+=mm.str()+nn.str();
                }
                	
            }//for
            s=str;
        }
        return s;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值