題目
The count-and-say sequence is the sequence of integers with the first five terms as following:
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 nth 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"
題目大意
n=1時(shí)輸出字符串1院究;
n=2時(shí),數(shù)上次字符串中的數(shù)值個(gè)數(shù)灶似,因?yàn)樯洗巫址?個(gè)1,所以輸出11;n=3時(shí)交胚,由于上次字符是11际邻,有2個(gè)1,所以輸出21腔彰;
n=4時(shí)叫编,由于上次字符串是21,有1個(gè)2和1個(gè)1霹抛,所以輸出1211搓逾。
依次類推,寫個(gè)countAndSay(n)函數(shù)返回字符串杯拐。
解題思路
使用遞歸解題
代碼
func countAndSay(n int) string {
if 1 == n {
return "1"
}
str1 := countAndSay(n-1)
len1 := len(str1)
var ret string
var c byte
c = str1[0]
count := 1
for i := 1; i < len1; i++ {
if str1[i] == c {
count++
continue
}
ret = ret + strconv.Itoa(count) + string(c)
c = str1[i]
count = 1
}
ret = ret + strconv.Itoa(count) + string(c)
return ret
}