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.
解:递归的思想以及利用StringBuilder对统计的数据进行连接。
public class Solution {
public String countAndSay(int n) {
if (n == 1){
return "1";
}
String temp = countAndSay(n-1);
int count = 1;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0;i < temp.length();i++){
//注意对最后一位的处理
if (i == temp.length() - 1){
if (count>1){
stringBuilder.append(count);
stringBuilder.append(temp.charAt(i-1));
}else {
stringBuilder.append(count);
stringBuilder.append(temp.charAt(i));
}
break;
}
if (temp.charAt(i+1) == temp.charAt(i)){
count ++;
}else {
stringBuilder.append(count);
stringBuilder.append(temp.charAt(i));
count = 1;
}
}
return stringBuilder.toString();
}
}