38. Count and Say
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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
题意:这题有点绕,报数,就是用中文的方法读这个数,比如111221 读作 三个1两个2一个1 输出312211,也就是对上一个字符串的描述
//
class Solution {
public:
string countAndSay(int n) {
string s="1";
for(int i =0;i<n-1;i++)
{
string ns;
for(int j=0;j<s.size();j++)
{
int k=j;
while(k<s.size() && s[k]==s[j]) k++;
ns+=to_string(k-j)+s[j]; //k-j 表示个数
j=k-1;
}
s=ns;
}
return s;
}
};
网友评论