leetcode count and say

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

题意:搞了半天没搞懂题意,是说给一个数量n,然后从1开始去按照这样一个顺序去排列,直到n :

1->1

一个1->11

两个->21

一个2一个1->1211

每次读取上一次的结果,然后用“几个几”这样的方式形成一个新的字符串


这里参照别人的方法,用到了stringstream,头文件sstream,2007年c++新的标准里有的,代替strstream,这里的各种类型与string 互相转化比较方便,有点像cout,cin的格式,声明一个stringstream类型的东西,有点像一小块内存一样,什么东西进去,然后用.str()这个方法,都能转化成string类型,比较方便,当然还有别的方法,以后用时再百度吧

代码:

class Solution {
public:
    string string_count(string &s){
        stringstream ss;
        int count = 0;
        char last = s[0];
        for(int i =0;i<=s.size();i++){
            if(s[i] == last){
                count++;
            }else{
                ss<<count<<last;
                count = 1;
                last = s[i];
            }
        }
        return ss.str();
    }

    string countAndSay(int n) {
        if(n<=0) return NULL;
        string s = "1";
        for(int i = 1; i < n ; i++){
            s = string_count(s);
        }
        return s;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值