Easy-题目50:38. Count and Say

转载 2016年05月30日 20:47:12

题目原文:
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.
题目大意:
按规律填空:1,11,21,1211,111221…….
规律是这样的:
1读作“1个1”并写为11;
11读作“2个1”并写为21;
21读作“1个2,1个1”并写为1211
……
求出这个数列的第n项
题目分析:
首先求出第n-1项,然后从头扫第n-1项的字符串,依次统计连续相同字符的个数。
源码:(language:java)

public class Solution {
     public  String countAndSay(int n) {
        if(n==1)
            return "1";
        else
        {
            String str=countAndSay(n-1);
            int i=0;
            String answer="";
            while(i<str.length())
            {
                int j=i;
                while(j<str.length() && str.charAt(i)==str.charAt(j))
                    j++;
                if(j>i)
                {
                    answer+=Integer.toString(j-i);
                    answer+=str.charAt(i);
                    i=j;
                }
                else
                    i++;
            }
            return answer;
        }
     }

}

成绩:
36ms,beats 3.03%,众数5ms,16.44%.
cmershen的碎碎念:
本题成绩较差,是因为使用了递归?不过如果不用递归难道不从n-1项推出n项吗?
本题的数列可在OEIS的A005150查到。

相关文章推荐

【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
  • 356

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(C,C++,Java,Python)

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

38. Count and Say

题目:Count and Say The count-and-say sequence is the sequence of integers beginning as follows: 1, 11,...

[leetcode-38]Count and Say

自动生成序列的一道题,想起来昨天比赛里遇见的另一道题,问C_∞序列第N位是多少,昨天死磕到最后也就是写了个垃圾代码,然后输入N>10就不能运行,觉得这类题的要点是要开两个序列,一个生成另一个后,然后拷...

<LeetCode OJ> 38. Count and Say(测试案例或有错)

38. Count and Say My Submissions Question Total Accepted: 66138 Total Submissions: 243196 Diffic...

LeetCode 38. Count and Say

这是我在LeetCode中做到的第一道需要用到递归思想的题目,因为自己对递归掌握的不好,这里做个笔记:题目大意为我们有一个 Count-and-say 的字符串序列,他的第一个元素是‘1’,后一个元素...

LeetCode38——Count and Say

LeetCode38——Count and Say 上一题对我来说实在太凶残了,所以我还是缓缓先做38题好了。。。 题意: 可以理解为求一个数组的第n项,而这个数组的通项公式可以这样理解: 第...

【LEETCODE】38-Count and Say

The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Easy-题目50:38. Count and Say
举报原因:
原因补充:

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