简繁EN

LeetCodeNo. 120

[LeetCode with Python] 38. Count and Say

Contents

Problem

Problem page: https://leetcode.com/problems/count-and-say/
Topics: String
Difficulty: Easy
Similar problems: (M) Encode and Decode Strings

The count-and-say sequence is the sequence of integers beginning as follows:
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 sequence.

Note: The sequence of integers will be represented as a string.


Analysis

It's mostly about the counting logic. In each round, I stop counting when I hit a different character. In the last round, though, I have to remember to stop counting explicitly because I've reached the end of the string src. It's like what the final $ symbol does in lexical analysis in compiler theory.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:

def doCountAndSay(self, src):
char = src[0]
num = 0
result = ""
for c in src:
if char == c:
num += 1
else:
result += (str(num) + char)
char = c
num = 1
result += (str(num) + char)
return result

# @return a string
def countAndSay(self, n):
if 0 == n:
return ""
elif 1 == n:
return "1"
result = "1" # str is a keyword
for i in range(1, n):
result = self.doCountAndSay(result)
return result

Article link: https://xnerv.wang/en/leetcode-count-and-say/