首页 > 代码库 > 【leetcode刷题笔记】Count and Say

【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 }