算法题--统计前一个字符串中每个数字的出现次数

image.png

0. 链接

题目链接

1. 题目

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.

Example 1:

Input: 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".

2. 思路:递归实现

  • 很显然,第n个字符串,是通过对第n-1个字符串中从左到右各个数字进行计数后,通过【出现次数】+【数字】的格式汇总后得到的
  • 实现方式:就是简单的递归,第n个字符串结果由第n-1个字符串统计而来,n=1的时候,直接返回1即可。

3. 代码

class Solution:
    def countAndSay(self, n: int) -> str:
        if  n == 1:
            return '1'
        else:
            result = []
            last_ch = ''
            last_count = 0
            pre_str = self.countAndSay(n - 1)
            for ch in pre_str:
                if last_ch == ch:
                    last_count += 1
                else:
                    if last_count > 0:
                        result.append(str(last_count))
                        result.append(last_ch)
                    last_ch = ch
                    last_count = 1
                    
            if last_count > 0:
                result.append(str(last_count))
                result.append(last_ch)
            
            return ''.join(result)

4. 结果

image.png

你可能感兴趣的:(算法题--统计前一个字符串中每个数字的出现次数)