leetcode 题解 || Count and Say 问题


problem:

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.

Hide Tags
  String
这是一个比较有意思的题目,计数-读数-产生新字符串。注意:我刚开始的做法是把 n 先转化成 string,
再对该字符串进行计数-读数操作,
后来发现题目已近给定初始字符串”1“,不过我还是把我的 int转换成 string部分代码帖出来了,
注释部分就是。


thinking:

(1)首先要读懂计数 - 读数的规律,比较有意思

(2)对重复的数计数,单个的数读一个什么数。


code:

class Solution {
public:
    string countAndSay(int n) {
       // string start = int_to_string(n);
       string start ="1";
        for(int i=0;i<n-1;i++ )
            start = factory(start);
        return start;
    }
protected:
    string factory(string str)
    {
        int count=1;//初始化为1 ,很巧妙 
        string res;
        if(str.empty())
            return str;
        if(str.size()==1)
        {
            res.push_back('1');
            res+=str;
            return res;
        }
        for(string::size_type i=0;i<str.size()-1;i++)//计数到倒数第二个
        {
            if(str.at(i)==str.at(i+1))
            {
                count++;
                if(i==str.size()-2) //到了末尾,别忘了存储
                {
                    char a=count+'0';
                    res.push_back(a);
                    res.push_back(str.at(i));
                }
            }
            else
            {
                char a=count+'0';
                res.push_back(a);
                res.push_back(str.at(i));
                count=1;
            }
        }//size()-1
        if(str.at(str.size()-1)!=str.at(str.size()-2))//处理最后一个字符
        {
            res.push_back('1');
            res.push_back(str.at(str.size()-1));
        }
       // factory(res,n--);
        return res;
    }
    /*
    string int_to_string(int n)  // int invert into string 
    {
        vector<char> array;
        string res;
        if(n<0)
            n=-n;
        while(n>0)
        {
            int a = n%10;
            n/=10;
            char b = '0'+a;
            array.push_back(b);
        }
        for(int i=array.size()-1;i>=0;i--)
          res.push_back(array.at(i));
        return res;
    }
    */
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值