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.
难度:简单
题目解析:给你一个数,第一个序列是 1, 第二个序列由第一个生成, 叫 一个1 ,写为 11
问:读n次后的结果
代码:
public class Solution {
public String countAndSay(int n) {
String result="1";
for(int i=1;i<n;i++){
result=Calculate(result);
}
return result;
}
public static String Calculate(String string){
char[] ch=string.toCharArray();
StringBuffer buffer =new StringBuffer();
for(int i=0;i<ch.length;i++){
char temp=ch[i];
int count=1;
while((i+1<ch.length)&&temp==ch[i+1]){
count++;
i++;
}
buffer.append(count);
buffer.append(temp);
}
return buffer.toString();
}
}