welcome to Smartcat's cnblog

leetCode练题——38. Count and Say

1、题目

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. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

 

题目解释:原题的意思就是用一个新的字符串描述上一个字符串,用数字表示上一个:
当n=1时:输出1;
当n=2时,解释1,1读作1个 ,表示为11;
当n=3时,解释上一个11,读作2个1,表示为21;(注意相同数字的描述)
当n=4时,解释上一个21,读作1个2,一个1,表示为1211;
当n=5时,解释上一个1211,读作1个1,1个2,2个1,表示为111221;
当n=6时,解释上一个111221,读作3个1,2个2,1个1,表示为312211;

2、我的解答

照搬大神的解法。。。。

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/2/5 10:54
 3 # @Author  : SmartCat0929
 4 # @Email   : 1027699719@qq.com
 5 # @Link    : https://github.com/SmartCat0929
 6 # @Site    : 
 7 # @File    : 38. Count and Say.py
 8 
 9 class Solution:
10     def countAndSay(self, n: int) -> str:
11         if n == 1:
12             return "1"
13         elif n == 2:
14             return "11"
15         string = "11"  #在11的基础上开始变换
16         for i in range(2, n):
17             newsb = []        #设立一个空列表
18             prev = string[0]  #记住第一个字符
19             cnt = 1
20             for symbol in string[1:]:
21                 if symbol == prev:
22                     cnt += 1            # 通过循环,记住第一个字符重复的次数
23                 else:
24                     newsb.append(str(cnt) + prev)   #若后续字符与第一个字符不重复,返回 1个”第一个字符“
25                     prev = symbol  #  改为记住后续字符
26                     cnt = 1  # 默认该字符出现次数为1
27             newsb.append(str(cnt) + prev)   #若后续字符与第一个字符重复,返回 几个”第一个字符“
28             string = "".join(newsb)
29         return string
30 print(Solution().countAndSay(4))

 

posted @ 2020-02-05 21:06  聪明猫  阅读(157)  评论(0)    收藏  举报