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.
public class Solution {
public String countAndSay(int n) {
String result = "1";
if(n==1) return result;
int level= 1;
for(int i =2;i <= n;i++){
char first = '0';
int count = 0;
StringBuilder ss = new StringBuilder();
for(int j = 0;j<result.length();j++){
char ch = result.charAt(j);
if(count != 0 && ch == first){
count++;
}
else {
if(count != 0 ){
ss.append(count);
ss.append(first);
}
first = ch;
count = 1;
}
}
ss.append(count);
ss.append(first);
result = ss.toString();
}
return result;
}
}