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. 

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道怎么初始化oldstring: 设置成第一个字符串“1”即可, 初始化数字个数也是1

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    sb.append(里面是字符串而不是sb,用来延长字符串) 

    [一句话思路]:

    当前的字符串都用oldstring来维护

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 求前i个数,直接用--n先减再给的情况,写起来比for方便

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    初始化oldstring: 设置成第一个字符串“1”即可, 初始化数字个数也是1

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

    public class Solution {
        /**
         * @param n: the nth
         * @return: the nth sequence
         */
        public String countAndSay(int n) {
            // write your code here
            //cc
            if (n <= 0) return "";
            String oldString = "1";
            
            //while loop
            while (--n > 0) {
                char[] oldChars = oldString.toCharArray();
                StringBuilder sb = new StringBuilder();
                
                for (int i = 0; i < oldChars.length; i++) {
                    int count = 1;
                    while ((i + 1) < oldChars.length && 
                    oldChars[i] == oldChars[i + 1]) {
                        count++;
                        i++;
                    }
                    sb.append(String.valueOf(count) + String.valueOf(oldChars[i]));
                }
                oldString = sb.toString();
            }
            
            return oldString;
        }
    }
    View Code
  • 相关阅读:
    JavaScript的for循环编写九九乘法表
    Python核心编程(切片索引的更多内容)
    js/jq宽高的理解与运用
    七月与安生:不管选择哪条路,都会是辛苦的 — —豆瓣老丑
    Linux命令入门
    jq滚动监听-导航滚动
    jQuery页面滚动监听事件及高级效果插件
    跟随鼠标移动展示内容
    用相对定位和负向移动完成图片相框阴影
    腾讯数据总监:运营人员必须掌握的APP基础数据分析体系(没有比这篇更系统全面的)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9142498.html
Copyright © 2011-2022 走看看