1170. Compare Strings by Frequency of the Smallest Character*
https://leetcode.com/problems/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.
C++ 实现 1
首先实现 f(w)
统计最小字母的频率. 之后, 统计 words
中每个字符串的 f(w)
, 保存到 records
, 然后对 records
排序. 对 queries
中的每个字符串, 计算每个字符串的 target = f(q)
, 查找 records
中 target
的 upper_bound
.
class Solution {
private:
int f(string &w) {
std::sort(w.begin(), w.end());
int i = 0;
while (i < w.size() && w[i] == w[0])
++ i;
return i;
}
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> records;
for (auto &w : words) records.push_back(f(w));
std::sort(records.begin(), records.end());
vector<int> res;
for (auto &q : queries) {
auto target = f(q);
int l = 0, h = records.size() - 1;
while (l <= h) {
int mid = l + (h - l) / 2;
if (records[mid] <= target) l = mid + 1;
else h = mid - 1;
}
res.push_back(l >= records.size() ? 0 : records.size() - l);
}
return res;
}
};
C++ 实现 2
upper_bound
可以直接用库函数. 另外 f(w)
也可以使用数组实现. 来自 LeetCode 的 Submission.
class Solution {
public:
int func(string str) {
int arr[26]= {0};
int s=str.size();
int temp=0;
for(int i=0;i<s;i++)
arr[str[i]-'a']++;
for(int i=0;i<26;i++)
if(arr[i]!=0)
{temp=arr[i];break;}
return temp;
}
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
int len=words.size();
int sze=queries.size();
vector<int> res;
vector<int> vec;
for(int i=0;i<len;i++)
vec.push_back(func(words[i]));
sort(vec.begin(),vec.end());
for(int i=0;i<sze;i++)
{
int val=func(queries[i]);
res.push_back(vec.end()-upper_bound(vec.begin(),vec.end(),val));
}
return res;
}
};