Count and Say
leetcode关于这题的说明比较含糊:
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 term of the count-and-say sequence.
题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。
解题思路:
采用动态规划的方式。当n=1时,直接返回‘1’。自底向上,然后根据n=index时返回的字符串计算出n=index+1时的字符串,并保存到数组curString中。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20def countAndSay(self, n):
if n==1:
return '1'
count = 1
index = 1
curString = ['', '1']
while index != n:
result = ''
cs = curString[index] + '*' # 加*是为了下面计算方便
for i in range(len(cs)-1):
if cs[i]==cs[i+1]:
count += 1
else:
result += str(count) + cs[i] # 加*的目的是为了方便处理最后一个字符
count = 1
index += 1
curString.append(result)
return curString[n]
采用正则表达:
leetcode上提供的另一种解题思路,尽管运行比较慢。
用作者的解释即: (.) captures one character and \1* covers its repetitions.
其中\1代表后向引用,表示表达式中,从左往右数,第一个左括号对应的括号内的内容。以此类推,\2表示第二个,\0表示整个表达式。1
2
3
4
5def 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