Use an array instead of a Map and store a custom struct,beats 81% c++.


  • 0
    S
     struct st{
            int f;
            char ch;
     };
        
        bool compare(struct st ob1,struct st ob2){
            return ob1.f>ob2.f;
        }
    class Solution {
    public:
        string frequencySort(string s) {
            if(!s.size())
                return s;
            if(s.size()==1)
                return s;
            vector<st> freq(123);
            for(char c:s){
                freq[(int)c].f++;
                freq[(int)c].ch=c;
            }
            std::sort(freq.begin(),freq.end(),&compare);
            string s1="";
            for(int i=0;freq[i].f!=0;i++){
                int count=freq[i].f;
                while(count){
                    s1+=freq[i].ch;
                    --count;
                }
           }
            return s1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.