LeetCode: Count and Say

技术LeetCode

问题

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_<span style="font-size: 12px;">th</span> 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 _个念作什么。

解决方法

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()
}
创建于2017年04月18日 15:04
阅读量 515
留言列表

暂时没有留言

添加留言