https://leetcode.com/problems/count-and-say/description/
题目
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
题目翻译
题目解析
参考答案
package main
import (
"fmt"
"strconv"
)
func nextSequence(now string) string {
b := []byte(now)
fmt.Println(now)
fmt.Println(b)
for i := 0; i < len(b); i++ {
fmt.Printf("%c ", b[i])
}
fmt.Println("*********")
nextSeq := ""
curCharacter := b[0]
curNum := 1
for i := 1; i < len(b); i++ {
if b[i] == curCharacter {
curNum++
} else {
strCurNum := strconv.Itoa(curNum)
nextSeq = nextSeq + strCurNum
nextSeq = fmt.Sprintf("%s%c", nextSeq, curCharacter)
curCharacter = b[i]
curNum = 1
}
}
strCurNum := strconv.Itoa(curNum)
nextSeq = nextSeq + strCurNum
nextSeq = fmt.Sprintf("%s%c", nextSeq, curCharacter)
return nextSeq
}
func countAndSay(n int) string {
now := "1"
for i := 1; i < n; i++ {
now = nextSequence(now)
}
return now
}
func main() {
fmt.Println("main", countAndSay(4))
}