zoukankan      html  css  js  c++  java
  • LeetCode -- Count and Say

    Question:

    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.

     Analysis:

    count-and-say 序列是指这样的序列:

    1, 11, 21, 1211, 111221, ...

    在数学上这个序列叫做“外观序列”,因为从1开始每一个数都是对上一个数的描述。而且有研究表明,相邻两数的长度之比越来越接近一个固定的数——康威常数(由科学家康威发现的)。

    但是题目要求的是:给出一个整数,输出第n个字符串序列。

    思路:因为是外观数列,因此没有什么数学表达式可以描述,第n个数仅仅可由前面一个数得到,而前面一个数又仅可以由再前面一个数得到……以此类推,因此,只有从第一个数开始,一直往后推,推到第n个数。开始怕时间会超,但是并没有~先这样做出来了,等以后想到好的方法再进行改善。

    Answer:

    public class Solution {
        public String countAndSay(int n) {
            int i = 1;
            String res = "1";
            if(n == 1)
                return res;
            //String s = countAndSay1(res);
            while(i < n) {
                res = countAndSay1(res);
                i++;
            }
            return res;
        }
        public String countAndSay1(String n) {
                StringBuffer buffer = new StringBuffer();
            char[] ch = n.toCharArray();
            int t = 1;
            for(int i=1; i<ch.length; i++) {
                    if(ch[i] == ch[i-1]) {
                        t++;
                    }
                    else {
                        buffer.append(Integer.toString(t));
                        buffer.append(ch[i-1]);
                        t = 1;
                    }
            }
            buffer.append(Integer.toString(t));
            buffer.append(ch[ch.length - 1]);
            return buffer.toString();
        }
        
    }
  • 相关阅读:
    查看客户端的IP地址,机器名,MAC地址,登陆名等信息
    查看sqlserver 2008中性能低下的语句
    搜索包含指定关键字的存储过程
    获得客户端详细信息以及每个进程的sql语句
    实战:sqlserver 日常检查脚本
    NIO的学习总结
    JavaWEB过滤器和监听器技术
    抽象工厂模式代码:
    详解 equals() 方法和 hashCode() 方法
    net.sf.json JSONObject与JSONArray使用实例
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4940959.html
Copyright © 2011-2022 走看看