leetcode:38. Count and Say

2018-08-20  本文已影响0人  唐僧取经

38. 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 nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Answer

package main

import "fmt"

type CountSay struct {
    value byte
    count byte
}

func countAndSay(n int) string {
    if n == 1 {
        return "1"
    }
    res := []byte{'1'}
    for i := 1; i < n; i++ {

        res = compute(res)
    }

    return string(res)
}

func compute(req []byte) []byte {
    res := []byte{}
    var temparr = make([]CountSay, 0)
    for j := 0; j < len(req); j++ {

        if len(temparr) != 0 && req[j] == temparr[len(temparr)-1].value {
            temparr[len(temparr)-1].count++
        } else {
            temparr = append(temparr, CountSay{req[j], '1'})
        }
    }

    for i := 0; i < len(temparr); i++ {
        res = append(res, byte(temparr[i].count))
        res = append(res, temparr[i].value)
    }
    return res

}

func main() {
    fmt.Println(string(countAndSay(6)))

}


上一篇下一篇

猜你喜欢

热点阅读