【题目】
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
【思路】感觉主要难点还是读懂题意,题目意思为:
当n = 1 时,字符串为1
当n = 2时,数前一个字符串,有1个1,所以为11
当n = 3时,数前一个字符串, 有2个1,所以为21
当n = 4时,数前一个字符串,有1个2,1个1,所以为1211.。。。。。。以此类推
很明显,递归
【Java代码】
public String countAndSay(int n){
StringBuffer result = new StringBuffer();
if(n == 1)
result.append('1');
else{
String pre = countAndSay(n-1);
char curr = pre.charAt(0);
int count = 0;
for(int i = 0 ; i < pre.length() ; i++){
if(curr == pre.charAt(i)){
count++;
}else{
result.append(count);
result.append(curr);
count = 1;
curr = pre.charAt(i);
}
}
result.append(count);
result.append(curr);
}
return result.toString();
}