count-and-say 计数和发言

原创 2018年04月16日 20:09:59

题目描述

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integer n, generate the n th sequence.

Note: The sequence of integers will be represented as a string. 

题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

典型的递归问题。

实现代码:

             class Solution {
public:
    string countAndSay(int n) {
        if(n == 1) return "1";
        //递归调用,然后对字符串处理
        string str = countAndSay(n-1) + "*";//为了str末尾的标记,方便循环读数
        int count = 1; //用于计算每个字符出现的次数;
        string s = "";
        for(int i = 0; i < str.length() - 1;i++) //因为增加了一个“*”,所以只能遍历到"*"之前的字符;
        {
            if(str[i] == str[i+1])
            {
                count++;//计数增加
            }
            else
            {
                s = s + to_string(count) + str[i];//个数在前,字符在后;
                count = 1;//初始化,为后面的字符做准备;
            }
        }
        return s;
    }
};

LeetCode之count-and-say sequence

问题描述:/** * The count-and-say sequence is the sequence of integers beginning as follows: * 1, 11, 2...
  • u011521382
  • u011521382
  • 2016-07-22 14:56:33
  • 2862

限时发言时间提示器 课程设计

  • 2010年03月12日 11:05
  • 204KB
  • 下载

Count and Say -- LeetCode

原题链接: http://oj.leetcode.com/problems/count-and-say/  这道题属于字符串操作的类型,算法上提高空间不大,只能是对于某一个数的串,读过去然后得到计数并...
  • linhuanmars
  • linhuanmars
  • 2014-03-07 04:43:20
  • 8440

著名的递推查数序列 Count and Say Sequence

题目源自于leetcode。 题目:The count-and-say sequence is the sequence of integers beginning as follows: 1, ...
  • luckyjoy521
  • luckyjoy521
  • 2013-12-06 20:40:45
  • 1538

Leetcode_38_count-and-say

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41257397 今天OJ可好几次,发现总是出错,最后才发现是...
  • pistolove
  • pistolove
  • 2014-11-18 22:27:53
  • 1406

【leetcode】第38题 Count and Say 题目+解析+代码

【题目】 The count-and-say sequence is the sequence of integers with the first five terms as follow...
  • buppt
  • buppt
  • 2017-08-20 11:36:36
  • 187

count-and-say

count-and-say
  • qq_18952073
  • qq_18952073
  • 2016-05-21 11:37:19
  • 168

leetcode 038 —— Count and Say

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 11122...
  • ziquanbang
  • ziquanbang
  • 2015-07-15 21:45:46
  • 102

LeetCode Count and Say 解题报告

LeetCode Count and Say 解题报告 如何数(shu 三声) 数(shu 四声):1,11,21,1211,111221,312211,13112221,1113213211...
  • worldwindjp
  • worldwindjp
  • 2014-12-05 15:09:28
  • 9843

LeetCode 38 Count and Say(字符串生成)

The count-and-say sequence is the sequence of integers with the first five terms as following: 1. ...
  • qq_26658823
  • qq_26658823
  • 2017-07-08 08:47:08
  • 800
收藏助手
不良信息举报
您举报文章:count-and-say 计数和发言
举报原因:
原因补充:

(最多只允许输入30个字)