码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-报数

时间:2018-11-04 12:37:12      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:idt   python   理解   while   aml   span   referer   auth   emacs   

LeetCode-报数

1 Easy-报数

1.1 题目描述

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

1 被读作 "one 1" ( "一个一" ) , 即 1111 被读作 "two 1s" ( "两个一" ), 即 2121 被读作 "one 2" , "one 1""一个二" , "一个一" ) , 即 1211

给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

1.2 示例 1:

输入: 1 输出: "1"

1.3 示例 2:

输入: 4 输出: "1211"

2 自己的答案

2.1 思路

  1. 前一项的报数值的读法为下一项的报数值,即当n为4时候,报数值为1211,所以当n为5的时候,按照n为4时报数值的读法"one 1 one 2 two 1s",报数值为111211
  2. 简言之,前一项的读法是相邻且相同的计数值+该数字所拼接的字符串.
  3. 再举例:n为5时报数值的读法是"Three 1s Two 2s one 1",所以n为6时报数值为312211

2.2 反思

  1. 一开始并没有理解题目的意思,后面在网上找了一下答案才稍微有点思路.
  2. 编码能力仍需提高.

2.3 代码

package algorithm.easy;

public class CounterAndSay {
    public static String solution(int n) {
        String old = "1";
        while (n > 1) {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < old.length(); ) {
                int j = i;
                while (j < old.length() && old.charAt(i) == old.charAt(j)) {
                    j++;
                }
                result.append(j - i).append(old.charAt(i));
                i = j;
            }
            old = result.toString();
            n--;
        }
        return old;
    }

    public static void main(String[] args) {
        System.out.println(solution(4));

    }
}

Date: 2018-11-04 11:19

Author: devinkin

Created: 2018-11-04 日 11:19

Validate

LeetCode-报数

标签:idt   python   理解   while   aml   span   referer   auth   emacs   

原文地址:https://www.cnblogs.com/devinkin/p/9903367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!