leetcode(16).38. Count and Say

来源:互联网 发布:最好的电子狗软件 编辑:程序博客网 时间:2024/06/05 11:29

题意:

对于一个整数序列:1, 11, 21, 1211, 111221, ...
第二个数是11是因为:第一个数是1-> 1个1 ->11

第三个数是21是因为:第二个数是11 -> 2个1 ->21

返回整数序列的第n个是什么

初步分析:根据n,从零开始遍历到n,一个一个的生成。

每一次都遍历上一次生成的字符串,如果相邻相同的时候,计数加1(相同的个数).最后每次循环结束:string更新为string+计数+那个数。

代码:

public class Solution {    public String countAndSay(int n) {        String now = "1";  //由题,从1开始        int count = 1;           for(int i=1; i<n; i++)        {            char pre[] = now.toCharArray();            now = "";            for(int j = 0;j<pre.length;j++)  //遍历要分析的字符串(上一个字符串)            {                 count = 1; //不相等就是一个                while(j+1<pre.length && pre[j] == pre[j+1])                {                    count++;                    j++;                }                now = now + count + pre[j];            }        }        return now;    }}



0 0