题目描述:
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 <= 20001 <= words.length <= 20001 <= queries[i].length, words[i].length <= 10queries[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;
}
};
本文介绍了一种用于比较字符串中最小字符频率的算法,并通过实际示例展示了如何利用该算法解决特定问题。文章详细解释了算法的实现过程,包括如何计算字符串的频率、如何对单词进行排序以及如何比较查询字符串与单词数组中的每个单词。
117

被折叠的 条评论
为什么被折叠?



