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.
和前面一道题差不多,中间加个临时string来udpate result.
有个小陷阱就是update 重复字符的时候记得要update 当前指针,否则output limit exceeded...另外这个题对内存还有要求。。。
class Solution {
public:
string countAndSay(int n) {
string res="1";
for (int i=2; i<=n; i++){
string tmp; // for given round;
for (int j=0; j<res.size(); j++){
char a=res[j];
int cnt=1;
int k=j+1;
while(k<res.size() && res[k]==res[j]){
k++;
cnt++;
j++;
}
tmp+=('0'+cnt);
tmp+=a;
}
res=tmp;
}
return res;
}
};