首页 > 编程语言 > 详细

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

时间:2015-10-31 22:59:44      阅读:211      评论:0      收藏:0      [点我收藏+]

题目来源:

  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

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

原文:http://www.cnblogs.com/chruny/p/4926290.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!