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

leetcode-38-Count and Say

作者头像
chenjx85
发布2018-05-21 18:34:56
5600
发布2018-05-21 18:34:56
举报

题目描述:

The count-and-say sequence is the sequence of integers with the first five terms as following:

代码语言:javascript
复制
1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

代码语言:javascript
复制
Input: 1
Output: "1"

Example 2:

代码语言:javascript
复制
Input: 4
Output: "1211"

要完成的函数:

string countAndSay(int n) 

代码:

代码语言:javascript
复制
#include<string>
#include<sstream>
    string int2str(int &i)//实现从int到string的转换
    {
        string s;
        stringstream ss(s);
        ss << i;
        return ss.str();
    }
    int count(string a,int b,int index)//在a中,从index这个位置开始,有多少个数字为b的,返回这个数量
    {
        int result=0;
        for(int i=index;i<a.size();i++)
        {
            if(a[i]==b)
            result++;
            else
            break;
        }
        return result;
    }
    string countAndSay(int n) //主要函数
    {
            string result="1";
        string result1;
        int result2;
        if(n==1)
        {
            return result;
        }
        while(--n)
        {
            int i=0;
            result1="";
            while(i<result.size())
            {
                result2=count(result,result[i],i);
                result1+=int2str(result2);
                result1+=result[i];
                i+=result2;
            }
            result=result1;
        }
        return result;
    }

说明:

1、这道题可能有的朋友不太明白题目在讲什么,说一下。

首先,n=1的时候,输出“1”的序列。

n=2的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”的序列。

n=3的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“2”个“1”,所以输出“21”的序列。

n=4的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的2,答案是“1”个“2”,所以输出12;数一下上一个序列中有多少个连续的1,答案是“1”个“1”,所以输出11。合起来就是“1211”。

n=5的时候,上一个序列中,从第一个数字开始,直到最后一个数字。数一下上一个序列有多少个连续的1,答案是“1”个“1”,所以输出“11”,数一下上一个序列中有多少个连续的2,答案是“1”个“2”,所以输出“12”,数一下上一个序列中有多少个连续的1,答案是“2”个“1”,所以输出“21”。合起来就是“111221”。

看明白之后,本题采用最暴力的方法去做,定义了三个函数。每个函数的功能都在注释中写了。自己跑一遍应该就看出来了。

2、c++的int2str在c++11中可以to_string(int)输出,比如cout<<to_string(123)+"908"<<endl;可以得到123908的输出。

但在c++11之前,就要使用#include<sstream>中的方法,像本文那样使用就可以了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 代码:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档