Let's define a function f(s)
over a non-empty string s
, which calculates the frequency of the smallest character in s
. For example, if s = "dcce"
then f(s) = 2
because the smallest character is "c"
and its frequency is 2.
Now, given string arrays queries
and words
, return an integer array answer
, where each answer[i]
is the number of words such that f(queries[i])
< f(W)
, where W
is a word in words
.
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.
o(min(n, m))首先肯定是要统计每个word的f值,由于每个单词的长度不超过10,那么f值肯定也不超过10,那就维护一个cnt表示所有word的f值出现的次数,再对这个cnt从后往前求一个前缀和,得到cnt[i]表示大于等于i的f值出现的次数
class Solution(object): def numSmallerByFrequency(self, queries, words): """ :type queries: List[str] :type words: List[str] :rtype: List[int] """ def f(word): cnt = [0] * 26 for c in word: cnt[ord(c) - ord('a')] += 1 for i in range(26): if cnt[i] != 0: return cnt[i] cnt = [0] * 12 for word in words: cnt[f(word)] += 1 for i in range(10, 0, -1): cnt[i] += cnt[i + 1] ans = [] for query in queries: ans.append(cnt[f(query) + 1]) return ans