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

    String

    Description:

    The count-and-say sequence is the sequence of integers with the first five terms as following:

    1.     1
    2.     11
    3.     21
    4.     1211
    5.     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 term of the count-and-say sequence.

    Note: Each term of the sequence of integers will be represented as a string.

    Example 1:

    Input: 1
    Output: "1"
    
    

    Example 2:

    Input: 4
    Output: "1211"
    

    个人觉得这个题意实在是反人类!!!

    在此说明一下题意:

    例如,5对应111221,6的结果就是对应读5得到的,也就是3个1、2个2、1个1,即:312211

    my Solution:

    public class Solution {
        public String countAndSay(int n) {
            StringBuffer sb = new StringBuffer("1");
            for (int i = 1; i < n; i++) {
                StringBuffer next = new StringBuffer();
                int count = 1;
                for (int j = 0; j < sb.length(); j++) {
                    if (j+1 < sb.length() && sb.charAt(j) == sb.charAt(j+1)) {
                        count++;
                    } else {
                        next.append(count).append(sb.charAt(j));
                        count = 1;
                    }
                }
                sb = next;
            }
            return sb.toString();
        }
    }
    
  • 相关阅读:
    SQL 执行进展优化
    初识SQL 执行顺序
    前端模块化开发的价值(转)
    js 闭包之一
    js模块开发(一)
    简单说说call 与apply
    js 爱恨情仇说 this
    说说 js String
    $Ajax简单理解
    SQL-如何使用 MongoDB和PyMongo。
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7262919.html
Copyright © 2011-2022 走看看