简繁EN

LeetCodeNo. 120

【LeetCode with Python】 38. Count and Say

目錄

題目

原題頁面:https://leetcode.com/problems/count-and-say/
題目型別:String
難度評價:Easy
類似題目:(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.


分析

主要是計數的邏輯。每一輪,遇到一個不同的字元時,就結束到該輪的計數。但是需要注意的是最後一輪的計數,因為遇到的是字串src的結尾,所以需要強制結束這一輪的計數,就類似於編譯原理詞法分析最後的那個$符號的作用。


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-count-and-say/