0%

LeetCode: Count and Say

问题

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 _n_th sequence.

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

翻译

数数问题是像如下顺序的整数:

1, 11, 21, 1211, 111221, ...

1被读作 "1个1" 或者 11

11被读作2个1或者21

21被读作1个2,然后1个1或者1211

给出整数 n_, 求出第 _n 个结果。

进一步解释:

1念作11, 11念作21, 21念作1211

求出第 _n _个念作什么。

解决方法

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
27
func countAndSay(n int) string {
if n == 1 {
return "1"
}
return getResult(countAndSay(n - 1))
}

func getResult(nStr string) string {
var curr rune
currCount := 1
var s bytes.Buffer
for _, v := range nStr {
if curr == v {
currCount++
} else {
if curr != 0 {
s.WriteString(strconv.Itoa(currCount))
s.WriteRune(curr)
}
curr = v
currCount = 1
}
}
s.WriteString(strconv.Itoa(currCount))
s.WriteRune(curr)
return s.String()
}