[LeetCode]题解(python):038-Count and Say

题目来源:

  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
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4926290.html

原文地址:https://www.cnblogs.com/chruny/p/4926290.html