leetcode1170. Compare Strings by Frequency of the Smallest Character

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1170. Compare Strings by Frequency of the Smallest Character相关的知识,希望对你有一定的参考价值。

题目如下:

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.

 

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

 

以上是关于leetcode1170. Compare Strings by Frequency of the Smallest Character的主要内容,如果未能解决你的问题,请参考以下文章

C++ compare函数字符串字典序比较

ZZNUOJ_用C语言编写程序实现1170:最长字符串(指针专题)(附完整源码)

C#中String的静态方法Compare(str1,str2)比较字符串大小

LeetCode 844. Backspace String Compare

Leetcode: Backspace String Compare

LeetCode - Backspace String Compare