zoukankan      html  css  js  c++  java
  • 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.

    链接:  http://leetcode.com/problems/count-and-say/

    一刷。这道题很简单,边界问题缺有点麻烦,其实也不是麻烦,但是思维上有需要改进的地方:

    1.外循环几次,N=0和N=1是单独返回的,其实N>1的话,只要计算N-2次就可以了。N的第几个数,而循环则是经过几次处理,两个差了一次遍历

    2.每次循环结束时,只考虑了最后一个数字与之前不相等时候需要加到list后面,其实所有情况都需要考虑。只考虑特殊情况是错的!!!

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            if n == 0:
                return ''
            if n == 1:
                return '1'
            
            old = '1'
            new = []
            
            for seq in range(n - 1):
                for idx, val in enumerate(old):
                    if idx == 0:
                        prev = val
                        count = 1
                    else:
                        if val == prev:
                            count += 1
                        else:
                            new.extend([str(count), prev])
                            count = 1
                            prev = val
                else:
                    new.extend([str(count), prev])
                old = ''.join(new)
                new = []
            return old

     2/11/2017, Java

    犯的错误:

    1. StringBuilder初始化用String,不用char,区别是单引号和双引号;

    2. 如果不想额外特例判断长度,c和n应该初始化在index = 0的位置;

    3. 跳过相同的字符时,一定注意是否越界!

    4. ret.append(n-c)这句我不懂;

    5. c = n不是c++

     1 public class Solution {
     2     public String countAndSay(int n) {
     3         StringBuilder a = new StringBuilder("1");
     4         for (int i = 0; i < n - 1; i++) {
     5             a = count(a);
     6         }
     7         return a.toString();
     8     }
     9     StringBuilder count(StringBuilder s) {
    10         StringBuilder ret = new StringBuilder();
    11         int c = 0;
    12         int n = 0;
    13         while (n < s.length()) {
    14             while (n < s.length() && s.charAt(n) == s.charAt(c)) n++;
    15             ret.append((n - c));
    16             ret.append(s.charAt(c));
    17             c = n;
    18         }
    19         return ret;
    20     }
    21 }
  • 相关阅读:
    如何在solution中添加一个test case
    Solution中的auto test case组织方式
    如何使用SPY++查找
    VS2012如何更新下载TFS上面的代码到本地
    Mita和Maui
    Fuzzy test
    RSS FEED的应用
    iscroll横向滑动(当前页状态标记自动变化)
    jquery技巧(持续更新。。)
    jquery前端性能优化(持续添加。。。)
  • 原文地址:https://www.cnblogs.com/panini/p/5576639.html
Copyright © 2011-2022 走看看