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.
解题思路:该题算法很简单,关键是要理解题意:输出第n个count-and-say序列,count-and-say序列的生成如题,第1个为1,第二个为11,第三个为21。。。
public class Solution {
public String countAndSay(int n) {
String result=""+1;
String data=""+1;
if(n<0){
return null;
}
for(int i=1;i<n;i++){
int count=0;
int num=0;
result="";
for(int j=0;j<data.length();j++){
int tmp=data.charAt(j)-48;
if(count==0||tmp==num){
if(count==0){
num=tmp;
}
count++;
}else{
result=result+count+""+num;
count=1;
num=tmp;
}
}
result=result+count+""+num;
data=result;
}
return result;
}
}