zoukankan      html  css  js  c++  java
  • 【leetcode】1170. 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
  • 相关阅读:
    android5.0 BLE 蓝牙4.0+浅析demo搜索(一)
    android4.3 Bluetooth(le)分析之startLeScan分析
    android4.3 Bluetooth分析之扫描分析
    JAVA 如何将String进行大小写转换
    用Java将字符串的首字母转换大小写
    关于Android中设置闹钟的相对比较完善的解决方案
    Android闹钟 AlarmManager的使用
    关于Android中设置闹钟的相对完善的解决方案
    android闹钟实现原理
    Android利用AlarmManager执行定时任务
  • 原文地址:https://www.cnblogs.com/seyjs/p/11440748.html
Copyright © 2011-2022 走看看