class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
S="1"
for i in range(1,n): #控制外层的迭代次数
S=self.myfun(S)
return S
def myfun(self,S):
res=""
dict={}
for s in S:
if len(dict) is 0:#空时直接插入键与值
dict[s]=1
else: #这里又要分两种情况,一种是没有同名的存在,就要弹出并做处理 ;若已存在,则自增1
if s not in dict.keys():
name = list(dict.keys())[0]
count = dict[name]
res += str(count) + str(name)
del dict[name]
dict[s] = 1
else:
dict[s]+=1
if len(dict) is 1: #最后将剩余的一对键与值进行处理
name = list(dict.keys())[0]
count = dict[name]
res += str(count) + str(name)
return res
Leetcode 38. 数数并说
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.