Why memory limit exceeded ?


  • 0
    C
    class Solution {
    public:
        struct Node {
            int freq;
            char ch;
        };
        
        static bool lambda(struct Node a, struct Node b){
            return a.freq>b.freq;
        }
    
        string frequencySort(string s) {
            if(s.size() == 0)
                return "";
                
            string res = "";
            vector<Node> nums(256);
            
            for(char c : s){
                nums[(int)c].ch = c;
                nums[(int)c].freq++;
            }
            
            std::sort(nums.begin(), nums.end(), Solution::lambda);
            
            char c;
            for(int i=0; nums[i].freq > 0; i++){
                c = nums[i].ch;
                while(nums[i].freq--){
                    res = res + c; // If I replace this line with res += c, it gets Accepted!
                }
            }
            
            return res;
        }
    };

  • 1

    @cr7.abhishek

    Operator + in your statement res = rest+c will yields new string each time you try to append a character while if you directly execute the following res += c as you did, you are actually appending a character to a container as this mentions. If you would like to check details, you could check this reference for operator + between strings.


  • 0
    C

    @LHearen So its like the string pool in java, right?
    += works like Stringbuilder?


  • 0

    @cr7.abhishek Yes, you can read the posts I mentioned.


Log in to reply
 

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