题目原型:
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.
基本思路:
题目的基本意思就是,给出一个整数n,然后返回第n个序列,例如整数1返回“1”,读着one1;整数3返回“21”,读着two 1s;那么当取整数6,应该返回“312211”读着三个1,二个2,一个1。取整数7时,返回“13112221”。
public String countAndSay(int n) { String str = "1"; if(n==1) { return str; } for(int i = 2;i<=n;i++) { str = getTmp(str); } return str; } public String getTmp(String nstr) { String str = ""; char tmp; tmp = nstr.charAt(0); int count = 0; for(int i = 0;i<nstr.length();i++) { if(nstr.charAt(i)==tmp) { count++; } else { str+=count; str+=tmp; tmp = nstr.charAt(i); count = 1; } } str+=count; str+=tmp; return str; }
原文:http://blog.csdn.net/cow__sky/article/details/19927969