Advertisement
fsb4000

leetcode

Jan 23rd, 2022
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <array>
  2. using namespace std;
  3. static constexpr array<pair<int,int>, 256> init_array() {
  4.         array<pair<int,int>,256> alphabet;
  5.         for (int i = 0; i != 256; ++i) {
  6.             alphabet[i].first = 0;
  7.             alphabet[i].second = i;
  8.         }
  9.         return alphabet;
  10.     }
  11. class Solution {
  12. private:
  13.     static inline constexpr array<pair<int,int>,256> init = init_array();
  14. public:    
  15.     string frequencySort(string s) {
  16.         array<pair<int,int>,256> alphabet = init;
  17.         for (unsigned char c : s) {
  18.             ++alphabet[c].first;
  19.         }
  20.         sort(alphabet.begin(), alphabet.end(), std::greater{});
  21.         string res;
  22.         res.reserve(s.size());
  23.         for (int i = 0; i != 256 && alphabet[i].first != 0; ++i) {
  24.             for (int j = 0; j != alphabet[i].first; ++j) {
  25.                 res.push_back(alphabet[i].second);
  26.             }
  27.         }
  28.         return res;
  29.     }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement