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 }
  • 相关阅读:
    react-native window下创建Hello(解决创建一路的坑)
    vue2.0 监听滚动 锚点定位
    vue-awesome-swiper 轮播图使用
    vue和react区别
    vuex 管理状态
    vue 解决axios 跨域问题
    判断一个对象是否为空? js
    微信小程序中的自定义组件(components)
    深入理解ES6箭头函数中的this
    vue中组件的data为什么是一个函数
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3860018.html
Copyright © 2011-2022 走看看