LeetCode38. 外观数列Golang版
1. 问题描述
给定一个正整数 n ,输出外观数列的第 n 项。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
你可以将其视作是由递归公式定义的数字字符串序列:
countAndSay(1) = “1”
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
前五项如下:



2. 思路
2.1. 思路1
遍历数组,统计连续相同元素的个数。
3. 代码
3.1. 代码1
func countAndSay(n int) string{
str := "1"
for i := 1; i < n; i++ {
str = next(str)
}
return str
}
func next(str string) string {
var res []byte
current := str[0]
count := 0
for i := 0; i < len(str); i++ {
if str[i] == current {
count ++
if i == len(str)-1{
res = append(res,[]byte(strconv.Itoa(count))...)
res = append(res,current)
}
} else {
res = append(res,[]byte(strconv.Itoa(count))...)
res = append([]byte(res),current)
count = 0
current = str[i]
i--
}
}
return string(res)
}
本文介绍了LeetCode第38题的解决方案,主要使用Golang编程语言。通过遍历和统计连续相同字符来生成外观数列的下一个数。代码清晰地展示了如何将给定的数转化为其描述形式。
275

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



