字符串出现次数TopK问题的python实现:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# return topK string
# @param strings string字符串一维数组 strings
# @param k int整型 the k
# @return string字符串二维数组
#
class Solution:
def topKstrings(self , strings: List[str], k: int) -> List[List[str]]:
# write code here
if k==0:
return []
mydict = {}
# 构建哈希表
for strs in strings:
if strs not in mydict:
mydict[strs] = 1
else:
mydict[strs]+=1
# 对哈希表排序
mylist = []
for key, val in mydict.items():
mylist.append([key, val])
ans_list = self.fasts(mylist)
if k>=len(ans_list):
return ans_list
else:
return ans_list[:k]
def fasts(self, mylist):
if len(mylist)<=1:
return mylist
a = mylist[0]
left = [i for i in mylist[1:] if (i[1]>a[1] or (i[1]==a[1] and i[0]<a[0]))]
right = [i for i in mylist[1:] if (i[1]<a[1] or (i[1]==a[1] and i[0]>a[0]))]
return self.fasts(left)+[a]+self.fasts(right)