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.
Analysis:
The idea is simple, string operation. Compare current char with next char, if same count++, else record this to result.
Java
public String countAndSay(int n) {
String result = "1";
if(n==1) return result;
int level = 1;
while(level<n){
char last = result.charAt(0);
int count =0;
StringBuffer seq = new StringBuffer();
for(int i=0;i<result.length();i++){
if(last == result.charAt(i)){
count++;
continue;
}else {
seq.append(count);
seq.append(last);
last = result.charAt(i);
count=1;
}
}
seq.append(count);
seq.append(last);
result = seq.toString();
level++;
}
return result;
}
c++
string countAndSay(int n) {
string result = "1";
int level = 1;
while(level < n){
stringstream seq;
char last = result[0];
int count =0;
for(int i=0; i<=result.size();i++){
if(result[i] == last){
count++;
continue;
}
else{
seq<<count<<last;
count = 1;
last = result[i];
}
}
result = seq.str();
level++;
}
return result;
}