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.
题目分析:
此题使用StringBuffer构造数组,注意StringBuffer在执行函数操作后返回的仍然是该对象,需要输出数组时不要忘了使用toString函数。
题目代码:
public class Solution {
public static String countAndSay(int n) {
StringBuilder curr = new StringBuilder("1");
StringBuilder now = new StringBuilder();
for(int i=1;i<n;i++){
now = curr;
char say = now.charAt(0);
curr = new StringBuilder();
int count = 1;
for(int j=1;j<now.length();j++){
if(now.charAt(j)!=say){
curr.append(count).append(say);
count = 1;
say = now.charAt(j);
}
else count++;
}
curr.append(count).append(say);
}
return curr.toString();
}
}