【leetcode】1170. Compare Strings by Frequency of the Smallest Character
题目如下:
Let's define a function
f(s)
over a non-empty strings
, which calculates the frequency of the smallest character ins
. For example, ifs = "dcce"
thenf(s) = 2
because the smallest character is"c"
and its frequency is 2.Now, given string arrays
queries
andwords
, return an integer arrayanswer
, where eachanswer[i]
is the number of words such thatf(queries[i])
<f(W)
, whereW
is a word inwords
.
Example 1:
Input: queries = ["cbd"], words = ["zaaaz"] Output: [1] Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] Output: [1,2] Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j]
,words[i][j]
are English lowercase letters.
解题思路:本题比较简单,先求出words中每个单词的最小字母的出现频次,并保存到list中。接下来计算queries中每个单词的最小字母的出现频次,并与words中的频次比较。比较的方法可以用二分查找,这样很快就能得到结果。
代码如下:
class Solution(object): def numSmallerByFrequency(self, queries, words): """ :type queries: List[str] :type words: List[str] :rtype: List[int] """ def calc(word): min_v = word[0] dic = {} for i in word: dic[i] = dic.setdefault(i,0) + 1 min_v = min(min_v,i) return dic[min_v] words_count = [] for word in words: words_count.append(calc(word)) words_count.sort() res = [] import bisect for query in queries: count = calc(query) inx = bisect.bisect_right(words_count,count) res.append(len(words_count) - inx) return res