Leetcode38:count and say数一数,说一说

题目解析:给定一个整型数n,要求按规律的第n个string。规律如下:

n=1        string = "1";
n=2        string = "11";        //1个1
n=2        string = "21";        //2个1
n=4        string = "1211";      //1个2,1个1
n=5        string = "111221";    //1个1,1个2,2个1
n=6        string = "312211";    //3个1,2个2,1个1

以此类推,求第n个字符串string。

解题思路就是,从第一个string依次写,一直写到第n个string。第n个string就是对第n-1个string依次数它字符的数目,保存即可。

我的答案:

class Solution {
public:
    string countAndSay(int n) {
        string present, next;
        char ch;
        int num=0,i;
        
        present.push_back('1');    // 当前字符串为"1"

        while(--n){ 
            ch = present[0];
            next.clear();
            for(i=0;i<present.size();++i){
                if(present[i]==ch)    //计数字符的数目
                    ++num;
                else{
                    next.push_back('0'+num);    //字符表示数字的时候要用'0'+ (int)num
                    next.push_back(present[i-1]);
                    num = 1;
                    ch = present[i];
                }                   
            }
            next.push_back('0'+num);
            next.push_back(present[i-1]);
            present.clear();
            present = next;
            num = 0;
        }
        
        return present;
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值