題目來源:
https://leetcode.com/problems/count-and-say/
題意分析:
字符串列符合這樣的規則:連續出現字符的次數+上這個字符。比如“11”就是2個1,也就是得到“21”。初始字符串是“1”。輸入一個正整數n,輸出滿足這個規則的第n個數。
題目思路:
這是一道簡單題。寫一個函數,輸入一個字符串,得到滿足規則的下一個字符串。重復這個函數n次就可以了。
代碼(python):

1 class Solution(object): 2 def countStr(self,s): 3 count = 0;ans = "";tmp = s[0] 4 for i in range(len(s)): 5 if s[i] == tmp: 6 count += 1 7 else: 8 ans += str(count) + tmp 9 tmp = s[i];count = 1 10 ans += str(count) + tmp 11 return ans 12 def countAndSay(self, n): 13 """ 14 :type n: int 15 :rtype: str 16 """ 17 ans = '1' 18 while n > 1: 19 ans = self.countStr(ans) 20 n -= 1 21 return ans
轉載請注明出處:http://www.cnblogs.com/chruny/p/4926290.html