问题链接:
https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/886/
解题思路:
递归
遇到难题:
原始思路是直接使用dictionary记录数字出现的次数,后来发现dictionary不能保证次序。
抛弃上面思路,直接用count
最终解法如下:
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n < 0:
return ""
elif n == 1:
return "1"
else:
s = self.countAndSay(n - 1)
result = []
tmp = s[0]
count = 0
for i in range(len(s)):
if s[i] == tmp:
count += 1
else:
result.append(str(count))
result.append(tmp)
count = 1
tmp = s[i]
result.append(str(count))
result.append(tmp)
return ''.join(result)
网友评论