LeetCode 38. Count and Say

来源:互联网 发布:怎样查到淘宝的访客数 编辑:程序博客网 时间:2024/06/04 19:51

38. Count and Say

一、问题描述

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.

二、输入输出

三、解题思路

读懂了题并不是很难,题目的意思就是让你数处有多少个1多少个2.如果是1个1,就输出11,读作1个1.如果是11(2个1)就读作21(2个1)依次类推

递归解法

  • 使用递归可以做这道题,退出条件是n=1 n=2 然后递归调用自己返回n-1时的string,根据n-1时的string得到n对应的string
  • 由n-1到n的递推关系如下:依次遍历直到出现不一样的字符,记录下相同字符的个数然后输出,并更新当前遍历下标
class Solution {public:    string countAndSay(int n) {        if(n == 1) return "1";        if(n == 2) return "11";        string last = countAndSay(n-1);        stringstream ss;        for (int i = 0; i < last.size(); ) {            char first = last.at(i);            int j = i + 1;            while(j < last.size() && last.at(j) == first)j++;            ss << (j - i) << first;            i = j;        }        return ss.str();    }};