Compare Strings by Frequency of the Smallest Character Solutions in C++
Number 1170
Difficulty Easy
Acceptance 58.6%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/// Author : Hao Chen// Date : 2019-10-01class Solution {public:vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {cout << queries.size() << " : " << words.size() << endl;vector<int> freq;for (auto w : words) {freq.push_back(f(w));}sort(freq.begin(), freq.end());vector<int> result;for (auto q : queries) {result.push_back(binary_search(freq, f(q)));}return result;}int f(string& s) {char ch = 'z' + 1; //stroe the smallest charint cnt = 0; //stroe the frequency of the smallest charfor (auto c : s) {if (c < ch) { //find the smaller char, reset the countcnt = 1;ch = c;} if (c == ch) {cnt++;}}return cnt;}int binary_search(vector<int> &v, int target) {int low=0, high=v.size()-1, mid;while (low < high) {mid = low + (high - low) / 2;if ( v[mid] > target) {high = mid -1;} else if (v[mid] <= target) {low = mid + 1;}}low = v[low] > target ? low : low + 1;return v.size() - low;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character//// Author : liuyubobobo/// Time : 2019-08-24#include <iostream>#include <vector>using namespace std;/// Presum/// Time Complexity: O(|words| + |queries|)/// Space Complexity: O(1)class Solution {public:vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {vector<int> vec(11, 0);for(const string& word: words)vec[f(word)] ++;for(int i = vec.size() - 1; i >= 1; i --)vec[i - 1] += vec[i];vector<int> res;for(const string& q: queries)res.push_back(vec[f(q) + 1]);return res;}private:int f(const string& s){vector<int> freq(26, 0);for(char c: s)freq[c - 'a'] ++;for(int e: freq) if(e) return e;return 0;}};void print_vec(const vector<int>& vec){for(int e: vec) cout << e << " "; cout << endl;}int main() {vector<string> queries1 = {"cbd"}, words1 = {"zaaaz"};print_vec(Solution().numSmallerByFrequency(queries1, words1));// {1}vector<string> queries2 = {"bbb","cc"}, words2 = {"a","aa","aaa","aaaa"};print_vec(Solution().numSmallerByFrequency(queries2, words2));// {1, 2}return 0;}