38. Count and Say

本文介绍了一种使用C++解决LeetCode上Count and Say问题的方法。通过两次不同的实现展示了如何将整数转换为字符串,并逐步生成指定次数的序列。第一次实现采用stringstream进行类型转换,第二次则使用了更简洁的to_string方法。

1刷
水题一题,直接按照字面意思来

PS,int转string
用stringstream ss;详细看代码

class Solution {
public:
    string countAndSay(int n) {
        string s = "1";
        string last = "1";
        for(int i = 2; i <= n; ++ i){
            s = "";
            int num = 1;
            char u = last[0];
            for(int j = 1; j < last.length(); ++ j){
                if(last[j] == last[j - 1]){
                    num++;
                    continue;
                }
                else{
                    stringstream ss;
                    ss << num;
                    string sss;
                    ss >> sss;
                    s += sss;
                    s += u;
                    num = 1;
                    u = last[j];
                }
            }
                    stringstream ss;
                    ss << num;
                    string sss;
                    ss >> sss;
                    s += sss;
                    s += u;


            last = s;
        }
        return s;
    }
};

2刷
用了比1刷更好看的代码
学习to——string(count)

class Solution {
public:
    string countAndSay(int n) {
        if(n == 0) return "";
        string s = "1";
        while(--n){
            string tmp = "";
            for(int i = 0; i < s.size(); ++ i){
                int count = 1;
                while(i + 1 < s.size() && s[i] == s[i + 1]){
                    count++;
                    i++;
                }
                tmp += to_string(count) + s[i];
            }
            s = tmp;
        }
        return s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值