一、题目
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.
二、解题思路
题目的意思就是:“计数”和“说数”,后一个就是前一个的表达,如果1211,就是:1个1,1个2,两个1,写出来就是111221。给定字符串是 s,相邻的相等的子串进行计数,结果为 str(count)+str[ i ]
三、代码
#coding:utf-8 def countStr(strs): counts = 0 s = "" i = 0 while i in range(len(strs)): #遍历字符串 for j in range(i,len(strs)): #遍历当前字符之后的字符 if strs[j] != strs[i]: counts = j - i s = s + str(counts) + strs[i] break if j == len(strs)-1: # 到最后一个字符时,应该单独考虑,因为python中的range范围包左不包右 counts = j -i + 1 s = s + str(counts) + strs[i] i = i+counts print(s) return s def countAndSay(n): """ :type n: int :rtype: str """ if n == 1: print(1) return 1 s = '1' while n > 1: s = countStr(s) n -= 1 return s if __name__ == '__main__': countAndSay(10)
四、“别人”代码
http://www.cnblogs.com/chruny/p/4926290.html
class Solution(object): def countStr(self,s): count = 0;ans = "";tmp = s[0] for i in range(len(s)): if s[i] == tmp: count += 1 else: ans += str(count) + tmp tmp = s[i];count = 1 ans += str(count) + tmp return ans def countAndSay(self, n): """ :type n: int :rtype: str """ ans = '1' while n > 1: ans = self.countStr(ans) n -= 1 return ans