Why is my solution Memory Limit Exceeded? C++


  • 0
    X

    The answer seems right.

    class Solution {
    public:
        string convert(string s, int nRows) {
            int i,j;
            string r="";
            for(j=1;j<=nRows;j++){
                if(j==1){
                    i=1;
                    while(i-1<s.length()){
                        r+=s[i-1];
                        i+=2*nRows-2;
                    }
                }
                else if(j==nRows){
                    i=nRows;
                    while(i-1<s.length()){
                        r+=s[i-1];
                        i+=2*nRows-2;
                    }
                }
                else{
                    i=j;
                    while(i-1<s.length()){
                        r+=s[i-1];
                        i+=nRows-1;
                    }
                }
            }
            return r;
        }
    };

  • 0
    D

    Your code get wrong in this case: when nRows = 1, 2*nRows - 2 = 0, hence the while loop executes infinitely.


Log in to reply
 

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