1170. 比较字符串最小字母出现频次
原始题目链接:https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character/
定义一个函数 f(s),统计 s 中(按字典序比较)最小字母的出现频次 ,其中 s 是一个非空字符串。
例如,若 s = “dcce”,那么 f(s) = 2,因为字典序最小字母是 “c”,它出现了 2 次。
现在,给你两个字符串数组待查表 queries 和词汇表 words 。对于每次查询 queries[i] ,需统计 words 中满足 f(queries[i]) < f(W) 的 词的数目 ,W 表示词汇表 words 中的每个词。
请你返回一个整数数组 answer 作为答案,其中每个 answer[i] 是第 i 次查询的结果。
解题思路:
统计字符串数组中每个字符串里面的最小字符的个数,用一个列表推到就可以完成,min(str)可以获得最小的字符,str.count(char)可以计算出该字符串中char字符的个数。
题目要求返回queries中每个字符串的最小字符和words中每个字符串的最小字符个数的比较,所以先计算words,再遍历queries中的字符串,每个字符串都和整个words结果比较,最后借用了满足条件的words中的字符个数,返回答案,具体实现看代码及注释。
代码实现:
class Solution:
def get_min_letter_freq(self, s:str)->int:
if not s:
return 0
freq_dict = collections.Counter(s)
return freq_dict[0][1]
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
# 统计words中最小字符的数目
words_min_ch_num = [word.count(min(word)) for word in words]
res = []
# 遍历数组queries中的字符串,计算最小字符的数目,与words_min_ch_num的所有元素对比
for query in queries:
y = query.count(min(query))
# 答案要求返回数目数组,直接计算符合条件的x的个数就是最后的答案
res.append(len([x for x in words_min_ch_num if x > y]))
return res
参考文献:
https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character/solution/python-by-philhsu/