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.


    题解:简单的模拟题,但是感觉题目叙述的不是特别清楚。

    一开始给定一个“1”,把它说出来就是“one one”,写成串就是11,这样就得到了第二个串11;

    把第二个串说出来就是“two one”,写成串就是21,这样就得到了第三个串21;

    把第三个串说出来就是“one two one one”,写成串就是1211,这样就得到了第四个串1211;

    ......

    题目求的是第n个串。

    设置一个StringBuffer存放当前串“说出来的结果”,然后根据n的大小不断循环,最终得到第n个串即可。

    代码如下:

     1 public class Solution {
     2     public String countAndSay(int n) {
     3         String accumu = "1";
     4         
     5         while(--n > 0){
     6             StringBuffer sb = new StringBuffer();
     7             char[] faster = accumu.toCharArray();
     8             for(int i = 0;i < faster.length;){
     9                 int count = 1;
    10                 char now = faster[i];
    11                 i++;
    12                 while(i<faster.length && faster[i]== faster[i-1] ){
    13                     count++;
    14                     i++;
    15                 }
    16                 sb.append(String.valueOf(count)+now);
    17             }
    18             accumu = sb.toString();
    19         }
    20         return accumu;
    21     }
    22 }
  • 相关阅读:
    PHP中使用CURL实现GET和POST请求
    ecstore关于smarty语法调用
    Linux 定时任务详解
    fzu 1753 Another Easy Problem
    zoj 2562 More Divisors
    poj 2992 Divisors
    UVA10078多边形判断凹凸性
    UVA10002求凸包的质心
    UVA10088多边形内整点个数计算(计算几何)
    HDU 1824 简单2-sat
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3860018.html
Copyright © 2011-2022 走看看