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.
1 class Solution(object): 2 def countAndSay(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 s = '1' 8 for _ in range(n - 1): 9 s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s) 10 return s
re.sub(pattern,repl,string,count=0,flags=0)实现正则替换
(.)\1*
.匹配任意一个字符
()组成一个group
\1和第一个group一样
lambda用来创建匿名函数
m.group()返回整个匹配
m.group(1)返回第一个匹配的group
1 class Solution(object): 2 def countAndSay(self, n): 3 """ 4 :type n: int 5 :rtype: str 6 """ 7 s = '1' 8 for i in range(n-1): 9 count = 1 10 temp = [] 11 for index in range(1, len(s)): 12 if s[index] == s[index-1]: 13 count += 1 14 else: 15 temp.append(str(count)) 16 temp.append(s[index-1]) 17 count = 1 18 temp.append(str(count)) 19 temp.append(s[-1]) 20 s = ''.join(temp) 21 return s
for index in range(n)是从0开始循环的。