38. Count and Say
38.1 题目描述:
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”
38.2 解题思路:
- 思路一:首先这道题的意思是口语化计数,比如刚开始1,就是1个1,则为11;11为2个1,则为21;21为1个2,1个1,则为1211;1211为1个1,1个2,2个1,则为111221;以此类推。则很容易用递归的方法解出。首先构造口语化计数的函数,简单的对字符串进行遍历,计数每一个不同的字符的个数,然后返回新的。具体看代码,很简单。
38.3 C++代码:
1、思路一代码(6ms):
class Solution102 {
public:
string say(string s)
{
int l = s.length()-1;
string t = "";
int i = 0;
int count = 1;
int flag = 0;
while (i<l)
{
if (s[i]==s[i+1])
{
count++;
flag = 0;
}
else
{
string temp = to_string(count);
t = t + temp + s[i];
count = 1;
flag = 1;
}
i++;
}
if (flag == 0)
{
string temp = to_string(count);
t = t + temp + s[i];
}
else
{
t = t + "1" + s[i];
}
return t;
}
string countAndSay(int n) {
if (n < 1)
return "";
string f="1";
while (n>1)
{
f = say(f);
n--;
}
return f;
}
};
38.4 Python代码:
1、思路一代码(49ms):
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
f="1"
def say(s):
i=0
t=""
count=1
flag=0
while i<len(s)-1:
if s[i]==s[i+1]:
count+=1
flag=0
else:
t=t+str(count)+s[i]
count=1
flag=1
i+=1
if flag==0:
t=t+str(count)+s[i]
else:
t=t+"1"+s[i]
return t
while n>1:
f=say(f)
n-=1
return f