I was trying this question: https://leetcode.com/problems/sort-characters-by-frequency/submissions/
How is s = s + c different from s+=c? where s is a string and c is a character.
I kept getting a memory limit exceeded error. Here's my code:
class Solution {
public:
struct comp {
bool operator()(const pair<char,int> a,const pair<char,int> b) {
return a.second <b.second;
}
};
string frequencySort(string s) {
priority_queue<pair<char,int>,vector<pair<char,int> >,comp> pq;
unordered_map<char,int> umap;
for(int i=0;i<s.length();i++)
umap[s[i]]++;
for(unordered_map<char,int>::iterator it=umap.begin();it!=umap.end();it++) {
pq.push(make_pair(it->first,it->second));
}
string res = "";
s="";
while(!pq.empty()) {
pair<char,int> temp = pq.top();
for(int i=0;i<temp.second;i++)
res = res + temp.first; // Error
pq.pop();
}
return res;
}
};Apparently, I finally found the error to be at the line marked in the code. I changed it to res+=temp.first and it worked! Any ideas why an assignment statement like this can cause a memory limit exceeded error?