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


    解题思路:

    直观的解题思路,只要把逻辑想清楚,就对了。本题自己想出来了,但是代码不够简洁,参考一些代码后优化如下。用StringBuilder。


    Java code:

    public String countAndSay(int n) {
            StringBuilder result = new StringBuilder();
            
            for(int i = 0; i < n; i++){
                StringBuilder s = new StringBuilder();
                if(result.length() == 0){
                    s.append(1);
                }else{
                    int count = 1;
                    for(int j = 1; j < result.length(); j++){
                        if(result.charAt(j) == result.charAt(j-1)){
                            count++;
                        }else {
                            s.append(count);
                            s.append(result.charAt(j-1));
                            count = 1;
                        }
                    }
                    s.append(count);
                    s.append(result.charAt(result.length()-1));
                }
                result = s;
            }
            return result.toString();
        }

    Reference:

    1. http://www.programcreek.com/2014/03/leetcode-count-and-say-java/

  • 相关阅读:
    总结html5
    css加载方式link和@import的区别!
    JavaScript
    log4j log for java
    异常
    内部类
    抽象类和接口,封装、继承、多态
    类和对象
    html 基础知识
    html表单
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865755.html
Copyright © 2011-2022 走看看