The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 term of the count-and-say sequence.
class Solution {
public String countAndSay(int n) {
String res ="1";
String cur = "1";
for(int i=1;i<n;i++){
char temp = cur.charAt(0);
int count=1;
res="";
for(int j=1;j<cur.length();j++){
if(cur.charAt(j)!=temp){
res = res+count + temp;
count=1;
temp = cur.charAt(j);
}
else
count++;
}
if(cur.charAt(cur.length()-1)==temp)
res = res+count+temp;
cur=res;
}
return res;
}
}