原题
https://leetcode.cn/problems/count-and-say/description/
思路
字典 + 循环
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def countAndSay(self, n: int) -> str:
d = {1: '1'}
if n == 1:
return d[1]
for i in range(2, n + 1):
s = d[i-1]
ans = ''
count = 0
char = ''
for j in range(0, len(s)):
if j == 0:
char = s[j]
count += 1
else:
if s[j] == s[j - 1]:
count += 1
else:
ans += str(count) + char
count = 1
char = s[j]
ans += str(count) + char
d[i] = ans
return d[n]
Go代码
func countAndSay(n int) string {
d := map[int]string{1: "1"}
if n == 1 {
return d[1]
}
for i := 2; i <= n; i++ {
// 之前的字符串
s := d[i-1]
ans := ""
count := 0
var char byte
for j := 0; j < len(s); j++ {
if j == 0 {
char = s[j]
count++
} else {
if s[j] == s[j-1] {
count++
} else {
// 将已压缩的字符加入结果
ans += string('0'+count) + string(char)
count = 1
char = s[j]
}
}
}
// 将已压缩的字符加入结果
ans += string('0'+count) + string(char)
d[i] = ans
}
return d[n]
}

被折叠的 条评论
为什么被折叠?



