402. Remove K Digits. Why it happened "Memory Limit Exceeded."


  • 0
    G
    
    
    string removeKdigits(string num, int k) {
            if(num.size()==0)return "0";
            while(num[0]=='0')
            {
                num.erase(num.begin());
                if(num.size()==0)return "0";
            }
            if(k<1)return num;
            
            if(num.size()<k)return num;
            if(num.size()==k)return "0";
            for(int i=0;i<num.size()-1;i++)
                if(num[i]>num[i+1])
                {
                    num.erase(num.begin()+i);
                    // cout<<num.size()<<endl;
                    return removeKdigits(num,k-1);}
            num.erase(num.begin()+num.size()-1);
            
            return removeKdigits(num,k-1);
        }
    
    

  • 0

    @gaoqihang To get help, I would strongly suggest you to read the instructions on how to format your code properly. No one wants to read unformatted code :)


  • 1

    Because you use recursion and thus hold many different long strings in memory at the same time. Btw, I'm typing this before opening your topic, i.e., before seeing what you're doing. Just basing my guess on your title :-)

    Ok now I've had a quick look and think I was right.

    @1337c0d3r As I believe I have just demonstrated, the problem can be identified without reading the code :-D


  • 0
    G

    @StefanPochmann I am editing it. sorry about that. It would be quick before I understand how to format the codings. Thanks


  • 1

    @gaoqihang BTW to format code you use three backquotes not single quotes. (It is the little key below your ESC key).


  • 0
    G

    @1337c0d3r I get it! Thanks..That's good now.


  • 0
    G

    Thanks guys. I solved this problem. Now it is accepted! When I do recursive, it produced so many string variables. So I use a global string variable instead of generating new variables. Here is my new coding:

    string str;
        string removeKdigits(string num, int k) {
            str=num;
            return removeKdigits2(k);
            
        }
        string removeKdigits2(int k)
        {
            if(str.size()==0)return "0";
            while(str[0]=='0')
            {
                str.erase(str.begin());
                if(str.size()==0)return "0";
            }
            if(k<1)return str;
            
            if(str.size()<k)return str;
            if(str.size()==k)return "0";
            for(int i=0;i<str.size()-1;i++)
                if(str[i]>str[i+1])
                {
                    str.erase(str.begin()+i);
                    // cout<<num.size()<<endl;
                    return removeKdigits2(k-1);}
            str.erase(str.begin()+str.size()-1);
            
            return removeKdigits2(k-1);
            
        }

Log in to reply
 

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