Question:
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.
Analysis:
count-and-say 序列是指这样的序列:
1, 11, 21, 1211, 111221, ...
在数学上这个序列叫做“外观序列”,因为从1开始每一个数都是对上一个数的描述。而且有研究表明,相邻两数的长度之比越来越接近一个固定的数——康威常数(由科学家康威发现的)。
但是题目要求的是:给出一个整数,输出第n个字符串序列。
思路:因为是外观数列,因此没有什么数学表达式可以描述,第n个数仅仅可由前面一个数得到,而前面一个数又仅可以由再前面一个数得到……以此类推,因此,只有从第一个数开始,一直往后推,推到第n个数。开始怕时间会超,但是并没有~先这样做出来了,等以后想到好的方法再进行改善。
Answer:
public class Solution { public String countAndSay(int n) { int i = 1; String res = "1"; if(n == 1) return res; //String s = countAndSay1(res); while(i < n) { res = countAndSay1(res); i++; } return res; } public String countAndSay1(String n) { StringBuffer buffer = new StringBuffer(); char[] ch = n.toCharArray(); int t = 1; for(int i=1; i<ch.length; i++) { if(ch[i] == ch[i-1]) { t++; } else { buffer.append(Integer.toString(t)); buffer.append(ch[i-1]); t = 1; } } buffer.append(Integer.toString(t)); buffer.append(ch[ch.length - 1]); return buffer.toString(); } }