Why my code get a memory limit exceed?


  • 1
    W
    class Solution {
    public:
        string convert(string s, int nRows) {
            int len = s.size();
            string result;
            for (int i = 0; i < nRows; i++) {
                if (i == 0 || i == nRows - 1) {
                    int j = i;
                    while (j < len) {
                        result.push_back(s[j]);
                        j += (2 * nRows - 2);
                    }
                } else {
                    int j = i;
                    while (j < len) {
                        result.push_back(s[j]);
                        j += (2 * nRows - 2 * (i + 1));
                        if (j < len) result.push_back(s[j]);
                        j += (2 * i);
                    }
                }
            }
            return result;
        }
    };
    

    I don't know why I got this error, and there is no input showed. I think I just use one string to store the result, and other three ints, it shouldn't be memory limit exceed. And all my loops can be exited correctly. I just feel so wired! Anyone can help me with this? Thank you!!


  • 2
    B

    Your codes in the following will loop forever when nRows == 1.

    while (j < len) { result.push_back(s[j]); j += (2 * nRows - 2); }

    You may add one more line at the very beginning as follows.

    if (nRows == 1) return s;


  • 0
    S

    really useful


Log in to reply
 

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