Leetcode 38 Count and Say

一开始题没读懂:
n是代表迭代次数

  • n = 1;返回”1”。
  • n = 2;查”1”,代表1个1。返回“11”.
  • n = 3;查”11“,代表2个1。返回”21”.
  • n = 4;查”21”,代表1个2,1个1。返回”1211”。

  • 解题思路:
    1、没什么说的,递归查,c++ string 可以用+来连接。
    2、对于字符串最后一个位置的判断。有两种方法,一种是让最后一个字符在循环之后处理,循环只进行length - 1次。一种是在递归返回的字符串上加标记符号。让字符串多一位。
class Solution {
public:
    string countAndSay(int n) {
        if (n == 1){return "1";}
        string str = countAndSay( n - 1);
        int count = 1;
        string s = "";
        for (int i = 0; i < str.size() - 1; ++i){
            if(str[i] == str[i+1]){
                count ++;
            } else{
                s += count+48;
                s += str[i];
                count = 1;
            }
        }
        s += (count +48);
        s += str[str.size() - 1];
        return s;
    }
        string countAndSay(int n) {
        if (n == 1){return "1";}
        string str = countAndSay( n - 1) + "*";
        int count = 1;
        string s = "";
        for (int i = 0; i < str.size() - 1; ++i){
            if(str[i] == str[i+1]){
                count ++;
            } else{
                s += count+48;
                s += str[i];
                count = 1;
            }
        }
        //s += (count +48);
        //s += str[str.size() - 1];
        return s;
    }
    };
    ---------------------------------------------------------
    以下部分是我刚开始理解错了,以为是输入有个数字,查to_string的个数。
    string func(int n) {
        char temp[2];
        string res;
        string src = to_string(n);
        int len = src.size();
        int left = 0;
        int count = 0;
        char last = src[0];
        while(left < len){
            if (src[left] == last){
                count += 1;
                left += 1;
            } else{
                res += count + 48;
                res += last;
                count = 1;
                last = src[left];
                left += 1;
            }
        }
        res += count + 48;
        res += last;
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值