38. Count and Say
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
class Solution {
public String countAndSay(int n) {
StringBuilder s=new StringBuilder();
if(n==1)
return "1";
char[] chs=countAndSay(n-1).toCharArray();
for(int i=0;i<chs.length;i++){
int count=1;
while(i<chs.length-1&&chs[i+1]==chs[i]){
count++;
i++;
}
s.append(count);
s.append(chs[i]);
}
return s.toString();
}
}