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.
class Solution {
public:
    vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
        vector<int> v;
        for(string word:words) v.push_back(f(word));
        sort(v.begin(),v.end());
        
        vector<int> result;
        for(string query:queries)
        {
            int freq=f(query);
            // 需要找到v中大于freq的元素个数,所以用upper_bound找到第一个大于freq的元素下标
            int i=upper_bound(v.begin(),v.end(),freq)-v.begin();
            result.push_back(v.size()-i);
        }
        return result;
    }
    
    int f(string s)
    {
        vector<int> count(26,0);
        for(char c:s) count[c-'a']++;
        for(int i=0;i<26;i++)
            if(count[i]>0) return count[i];
        return 0;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值