/*
38. Count and Say My Submissions QuestionEditorial Solution
Total Accepted: 78365 Total Submissions: 271881 Difficulty: Easy
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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
就是字符串递归统计,没啥好说的。注意的一点就是 当n=1时并不是返回“11”而是“1”所以要单独处理,其他的都比较守规矩。
*/
class Solution {
public:
string countAndSay(int n) {
//递归的简单应用
if(n<1)return "";
string res="1";
if(n==1)return res;
for(int i=1;i<n;i++){
res=convert(res);
}
return res;
}
string convert(string s){
string res="";
int count=0;
for(int i=0;i<s.size();i++){
if(i==0){
++count;
}else{
if(s[i]!=s[i-1]){
res+=to_string(count)+s[i-1];
count=1;
}else ++count;
}
}
res+=to_string(count)+s.back();
return res;
}
};