[leetcode:python]38.Count and Say
来源:互联网 发布:mac磁盘越来越小 编辑:程序博客网 时间:2024/05/22 06:40
题目:
The count-and-say sequence is the sequence of integers beginning as follows:
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 sequence.
Note: The sequence of integers will be represented as a string.
方法一:性能45ms
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ s = '1' for i in range(2, n+1): s = self.count(s) return s def count(self, s): t = '' count = 0 curr = '#' for i in s: if i != curr: if curr != '#': t += str(count) + curr curr = i count =1 else: count +=1 t += str(count) + curr return t
方法二:性能39ms
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ s = '1' for _ in range(n-1): let = s[0] tmp = '' count = 0 for l in s : if let == l: count += 1 else: tmp += str(count) + let let = l count = 1 tmp += str(count) + let s = tmp return s
这里的_
:Python中对于无需关注其实际含义的变量可以用_
代替,这就和for i in range(5)
一样,因为这里我们对i
并不关心,所以用_
代替仅获取值而已。
0 0
- [leetcode:python]38.Count and Say
- Leetcode-Count and Say-Python
- 【Leetcode】【python】Count and Say
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- HttpClient测试接口的封装(get和post)
- 5-11 关键活动
- QT 将含有中文字符的QString转化为char*类型
- 深入解析MySQL分区(Partition)功能
- 1075. PAT Judge (25)
- [leetcode:python]38.Count and Say
- 如何解决 Notice: Undefined index: submit in D:\wamp\www\bbs\add.php on line 9
- 建站工具
- 【tyvj4089】n^2(dp)
- Linux之使用MogileFS分布式文件系统并使用nginx实现反向代理
- IO流(1)--字节流
- Android Studio中JNI NDK开发(三)
- 常见dom树操作
- Spring第四篇【Intellij idea环境下、Struts2和Spring整合】