题目
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 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”
题意
找出题目中的规律,题目说的很详细。
C++语言
class Solution {
public:
string countAndSay(int n)
{
string s="1", temp;
int sum = 0, j;
if(n == 1)
return "1";
for(int i=2; i<=n; i++)
{
s+="0";
temp = "";
int sum =1;
for(int i=0; i+1<s.size(); i++)
{
if(s[i]!=s[i+1])
{
temp+=(to_string(sum)+s[i]);
sum = 1;
}
else
sum++;
}
s = temp;
}
return s;
}
};
Python语言
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res =""
s = "1"
for time in range(2,n+1):
res = ""
sum = 1
s = s + "0"
for i in range(0,len(s)-1):
if s[i]!=s[i+1]:
res = res + str(sum) + s[i]
sum = 1
else:
sum = sum + 1
s = res
return s