Why memory limit exceeded ?

  • 0
    class Solution {
        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;
            std::sort(nums.begin(), nums.end(), Solution::lambda);
            char c;
            for(int i=0; nums[i].freq > 0; i++){
                c = nums[i].ch;
                    res = res + c; // If I replace this line with res += c, it gets Accepted!
            return res;

  • 1


    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

    @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.