【字符串】1170. 比较字符串最小字母出现频次

题目:

解答:

思路就是先计算每个字符串中,26个字母每个出现的次数(fun函数的功能),然后就是二分查找找出答案。这里二分查找用的函数是标准库的 upper_bound。

 1 class Solution {
 2 public:
 3     vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) 
 4     {
 5         vector<int> q;
 6         vector<int> w;
 7 
 8         fun(queries, q);
 9         fun(words, w);
10 
11         sort(w.begin(), w.end());
12 
13         vector<int> ans;
14         for(int n : q)
15         {
16             auto ret = upper_bound(w.begin(), w.end(), n);
17             if(ret == w.end())
18             {
19                 ans.push_back(0);
20             }
21             else
22             {
23                 int pos = ret - w.begin();
24                 ans.push_back(w.size() - pos);
25             }
26         }
27 
28         return ans;
29     }
30 
31     // 计算每个字符串中,26个字母每个出现的次数
32     void fun(const vector<string>& strs, vector<int>& vec)
33     {
34         for(string s : strs)
35         {
36             for(int i = 0; i < 26; i++)
37             {
38                 char c = 'a' + i;
39                 int cur = count(s.begin(), s.end(), c);
40                 if(cur > 0)
41                 {
42                     vec.push_back(cur);
43                     break;
44                 }
45             }
46         }
47     }
48 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12824475.html