c++solution, but memory limit exceed, I don't understand why


  • 0
    C

    when input is "ababab..."(a very long string), it told me time limit exceeded. But I don't understand why and how to improve.
    class myChar{
    public:
    char c;
    long n;
    myChar(char cc,int nn){
    c=cc;
    n=nn;
    }
    myChar(char cc){
    c=cc;
    n=0;
    }
    };
    bool operator <(myChar a,myChar b){
    return a.n<b.n;
    }
    class Solution {
    public:
    string frequencySort(string s) {
    int len=s.length();
    vector<myChar>v;
    for(int i=0;i<128;i++){
    v.push_back(myChar(char(i)));
    }
    for(int i=0;i<len;i++){
    v[s[i]].n++;
    }
    sort(&v[0],&v[128]);
    string ans="";
    for(int i=127;i>=0;i--){
    if(v[i].n==0)break;
    long j=v[i].n;
    while(j--){
    ans=ans+v[i].c;
    }
    }
    return ans; }
    };
    '''>! Spoiler


Log in to reply
 

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