• 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 }
  • 相关阅读:
    <a>與<link>的區別
    103_linux如何安装mysql数据库?
    102_Centos7在虚拟机上开机时出现黑屏,怎么解决?
    101_war和war exploded的区别
    100_linux中passwd文件的用户解析
    099_linux基础命令三
    098_linux基本操作命令二
    097_linux如何配置jdk路径
    096_如何将linux的IP地址转换成静态ip地址?
    078_ip地址.DNS,子网掩码,网关分别是什么,又有什么作用?
  • 原文地址:https://www.cnblogs.com/panini/p/5576639.html
Copyright © 2020-2023  润新知