The count-and-say sequence is the sequence of integers with the first five terms as following:
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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
题目意思已经挺清楚的了,就是n的结果是根据n-1来推算的,代码如下
public String countAndSay(int n) {
StringBuilder sb = new StringBuilder("1");
for(int i = 1; i < n; i++){
sb = calc(sb.toString());
}
return sb.toString();
}
private StringBuilder calc(String s){
/**
* 循环上一次得到的结果
* 取得当前index的值与index+1...比较,直到不一样为止
* 这个个数 count + '当前值' 就是一段
* 但是我们需要跳过count,然后重复以上过程
* 得到的每一段都拼接起来得到对于当前n的结果
* 利用当前n的结果继续调用calc方法推算n+1的结果,如此往复得到最终结果
*/
StringBuilder sb2 = new StringBuilder("");
for(int i = 0;i < s.length();i++){
char a = s.charAt(i);
int count = 1 ;
while(i + 1 < s.length()){
char a_next = s.charAt(i+1);
if(a_next == a){
i ++;
count ++;
}else{
break;
}
}
sb2.append(count + "" + a);
}
return sb2;
}