前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Count and Say

Leetcode: Count and Say

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 17:32:42
3470
发布2019-01-22 17:32:42
举报
文章被收录于专栏:给永远比拿愉快

题目: 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.

思路分析: 我是先写了一个函数用于计算一个数字的下一个数字。计算过程是依次遍历当前数字统计相等的个数。

C++示例代码:

代码语言:javascript
复制
class Solution
{
public:
    //根据当前的number计算下一个number
    string countNext(string number)
    {
        string::size_type length = number.length();
        size_t count = 1;//记录相同数字的个数
        size_t index = 0;//遍历number的伪指针
        char curnum;//临时保存当前的数字
        string result;//最终结果
        //这层循环控制对number的遍历
        while (index < length)
        {
            curnum = number[index];
            //这层循环寻找相同数字并统计个数
            while (index < length)
            {
                //注意这里的index要先++然后进行比较判断,要不然会引起数组越界等问题
                if (index++ != length && curnum == number[index])
                {
                    //如果当前数字和其后的数字相等count++,统计有多少个当前数字
                    count++;
                }
                else
                {
                    //如果不相等就将count和curnum存入结果字符串中
                    result.push_back(count + '0');
                    result.push_back(curnum);
                    count = 1;
                    break;
                }
            }
        }
        return result;
    }

    string countAndSay(int n)
    {
        string number = "1";
        for (int i = 1; i < n; i++)
        {
            number = countNext(number);
        }
        return number;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年03月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档