题目:
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.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
solutions:
gosh!!!这个题目的定级虽然是easy,但是我真的看了一下午!!!
对于里面高级的lambda……wtf!
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
"""
第一种方法:
recursive implement
"""
if n == 1:
return '1'
s = self.countAndSay(n-1)
i,ch,tmp = 0, s[0], ''
for j in range(1,len(s)):
#若前后两个字符不同,则把结果加到tmp字符串中,更新i和ch
if s[j] != ch:
tmp += str(j-i) + ch #str(j-i)表示该数字出现的次数
i,ch = j,s[j]
tmp += str(len(s)-i) + ch #str(len(s)-i)表示如果前后字符都相同,计数整个s的长度再减去原有的i,作为现在的长度
return tmp
"""
第二种方法:
Solution 1和Solution 2的高级操作我不懂呐,欢迎交流
Solution 1 … using a regular expression
def countAndSay(self, n):
s = '1'
for _ in range(n - 1):
s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s)
return s
#b = lambda m: str(len(m.group(0))) + m.group(1) , s
# print(b)
#输出结果为
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B0440C2EA0>, '1')
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B044424BF8>, '11')
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B0440C2EA0>, '21')
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B044424BF8>, '1211')
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B0440C2EA0>, '111221')
(<function Solution.countAndSay.<locals>.<lambda> at 0x000000B044424BF8>, '312211')
关于re.sub()及re模块:https://blog.csdn.net/u014467169/article/details/51345657
re.sub的函数原型为:re.sub(pattern, repl, string, count)
re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))
其中第二个函数是替换后的字符串;本例中为'-'
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。
re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。
Solution 2 … using a regular expression
def countAndSay(self, n):
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(group)) + digit for group, digit in re.findall(r'((.)\2*)', s))
return s
Solution 3 … using groupby
def countAndSay(self, n):
s = '1'
#groupby()把迭代器中相邻的重复元素挑出来放在一起,
例如:
for key, group in itertools.groupby('AAABBBCCAAA'):
print (key, list(group))#注意要用list
#输出结果为
1 ['1', '1', '1']
2 ['2', '2']
1 ['1']
通过join函数可以将重复元素的个数和值加入到s字符串中
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s
"""