【leetcode】【38】Count and Say

来源:互联网 发布:软件开发工程师怎么样 编辑:程序博客网 时间:2024/06/05 23:54

一、问题描述

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.

二、问题分析

起始sequence为1,读作“one 1”那么下一个sequence为11,而11读作“two 1s”那么下一个sequence为21,以此类推。我们可以发现下一个sequence依赖与上一个sequence,而下一次操作下一个sequence又会作为上一个sequence出现,即循环。

三、Java AC代码

public String countAndSay(int n) {        if (n == 0) {return "";}String res = "1";char ch;int count;for(int i=1;i<n;++i){StringBuilder sb= new StringBuilder();count = 0;ch = res.charAt(0);for(int j=0;j<res.length();j++){if (res.charAt(j) == ch) {count++;} else {sb.append(count);sb.append(ch);ch = res.charAt(j);count = 1;}}sb.append(count);sb.append(ch);res = sb.toString();}return res;    }


0 0
原创粉丝点击