Leetcode 38. Count and Say

原创 2016年05月30日 23:30: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.

class Solution {
public:
    string countAndSay(int n) {
        if(n==1) return "1"; // base case
        string res,tmp = countAndSay(n-1); // recursion
        char c= tmp[0];
        int count=1;
        for(int i=1;i<tmp.size();i++)
            if(tmp[i]==c)
                count++;
            else {
                res+=to_string(count);
                res.push_back(c);   //res.push_back(c)的效果就是字符串拼接,相当于 res+=c ,两条语句合并可写为:res=res+to_string(count)+c;
                c=tmp[i];
                count=1;
            }
        res+=to_string(count);
        res.push_back(c);
        return res;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【leetcode c++】38 Count and Say

Count and Say The count-and-say sequence is the sequenceof integers beginning as follows: 1, 11, 2...
  • hqq39
  • hqq39
  • 2015-06-26 22:40
  • 310

Leetcode - 38. Count and Say

38. Count and Say题目简介 The count-and-say sequence is the sequence of integers beginning as follows:...

leetcode 38:count and say

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

【LEETCODE】38-Count and Say

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

leetcode38 Count and Say

package leetcode38; import java.util.ArrayList; /** * The count-and-say sequence is the sequence ...

LeetCode 38 Count and Say(计数与报数)

翻译计数报数序列按如下规律开始递增: 1,11,21,1211,111221,……1 读作“1个1”或11. 11 读作“2个1”或21. 21 读作“1个2,1个1”或1211.给定一个整数n,生成...
  • NoMasp
  • NoMasp
  • 2015-12-03 10:32
  • 3655

LeetCode 38. Count and Say

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

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

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

LeetCode 38 Count and Say(C,C++,Java,Python)

Problem: The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 2...

[leetcode-38]Count and Say

自动生成序列的一道题,想起来昨天比赛里遇见的另一道题,问C_∞序列第N位是多少,昨天死磕到最后也就是写了个垃圾代码,然后输入N>10就不能运行,觉得这类题的要点是要开两个序列,一个生成另一个后,然后拷...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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