Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d59ec42

Browse files
committed
add 38
1 parent 2e14d5d commit d59ec42

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2+
# 0038.count-and-say
3+
4+
```text
5+
给定一个正整数 n ,输出外观数列的第 n 项。
6+
7+
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。
8+
9+
你可以将其视作是由递归公式定义的数字字符串序列:
10+
11+
countAndSay(1) = "1"
12+
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
13+
前五项如下:
14+
15+
1. 1
16+
2. 11
17+
3. 21
18+
4. 1211
19+
5. 111221
20+
第一项是数字 1
21+
描述前一项,这个数是 1 即 " 一 个 1 ",记作 "11"
22+
描述前一项,这个数是 11 即 " 二 个 1 " ,记作 "21"
23+
描述前一项,这个数是 21 即 " 一 个 2 + 一 个 1 " ,记作 "1211"
24+
描述前一项,这个数是 1211 即 " 一 个 1 + 一 个 2 + 二 个 1 " ,记作 "111221"
25+
要 描述 一个数字字符串,首先要将字符串分割为 最小 数量的组,每个组都由连续的最多 相同字符 组成。然后对于每个组,先描述字符的数量,然后描述字符,形成一个描述组。要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
26+
27+
例如,数字字符串 "3322251" 的描述如下图:
28+
29+
30+
31+
32+
示例 1:
33+
34+
输入:n = 1
35+
输出:"1"
36+
解释:这是一个基本样例。
37+
示例 2:
38+
39+
输入:n = 4
40+
输出:"1211"
41+
解释:
42+
countAndSay(1) = "1"
43+
countAndSay(2) = 读 "1" = 一 个 1 = "11"
44+
countAndSay(3) = 读 "11" = 二 个 1 = "21"
45+
countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211"
46+
47+
48+
提示:
49+
50+
1 <= n <= 30
51+
52+
来源:力扣(LeetCode)
53+
链接:https://leetcode-cn.com/problems/count-and-say
54+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
55+
```

‎problems/0038.count-and-say/run.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package say
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
"strings"
7+
)
8+
9+
func Run() {
10+
s := countAndSay(6)
11+
fmt.Println(s)
12+
}
13+
14+
func countAndSay(n int) string {
15+
if n == 1 {
16+
return "1"
17+
}
18+
s := countAndSay(n - 1)
19+
res, start, length := make([]string, n), 0, len(s)
20+
for i := 1; i < length+1; i++ {
21+
if i == length {
22+
res = append(res, strconv.Itoa(i-start), string(s[start]))
23+
continue
24+
}
25+
if s[i] != s[start] {
26+
res = append(res, strconv.Itoa(i-start), string(s[start]))
27+
start = i
28+
}
29+
}
30+
return strings.Join(res, "")
31+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
package say
3+
4+
import "testing"
5+
6+
func TestRun(t *testing.T) {
7+
Run()
8+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /