题目:
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.
Note: Each term of the sequence of integers will be represented as a string.
这道题难度为easy,但是我对string的处理有问题,故摘取他人代码作学习笔记
class Solution {
public:
string countAndSay(int n) {
if(n==1)
return "1";
std::string result = std::to_string(1);
for(int i=1;i<n;++i)
result = getNext(result);
return result;
}
std::string getNext(std::string s){
std::string result;
int count = 1;
for(int i=0;i<s.size();++i){
while(i+1<s.size()&&s[i]==s[i+1]){
++count;
++i;
}
result += to_string(count)+s[i];
count = 1;
}
return result;
}
};