/**
* The count-and-say sequence is the sequence of integers beginning as follows:
* 1, 11, 21, 1211, 111221, ...
* 1is read off as"one 1"or11.
* 11is read off as"two 1 s"or21.
* 21is read off as"one 2, thenone 1"or1211.
* Given an integer n, generate the n th sequence.
* Note: The sequence of integers will be represented as a string.
*
* 题意是n=1时输出字符串1;
* n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;
* n=3时,由于上次字符是11,有2个1,所以输出21;
* n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。
* n=5时,由于上次字符串是1211,有1个1、1个2和2个1,所以输出111221.
*/
这道题真的需要好好理解一下子,用翻译来看的话,有点难理解,后来还是去百度相关博客才真正的理解它的意思。
/** * The count-and-say sequence is the sequence of integers beginning as follows: * 1, 11, 21, 1211, 111221, ... * 1is read off as"one 1"or11. * 11is read off as"two 1 s"or21. * 21is read off as"one 2, thenone 1"or1211. * Given an integer n, generate the n th sequence. * Note: The sequence of integers will be represented as a string. * * 题意是n=1时输出字符串1; * n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11; * n=3时,由于上次字符是11,有2个1,所以输出21; * n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。 * n=5时,由于上次字符串是1211,有1个1、1个2和2个1,所以输出111221. */ public class Main35 { public static void main(String[] args){ System.out.println(Main35.countAndSay(2)); } public static String countAndSay(int n) { if (n==1) { return "1"; } String str = countAndSay(n-1)+"*"; char[] ch = str.toCharArray(); int count = 1; String s = ""; for (int i=0;i<ch.length-1;i++){ if (ch[i] == ch[i+1]) { count++; }else{ s = s + count + ch[i]; count = 1; } } return s; } }