Why is my Java Code Memory Limit Exceeded


  • 0
    L
    public class Solution {
        public String convert(String s, int nRows) {
            String news = new String();
            int len = s.length(), i, j, x, y;
            if (nRows == 1)
                return s;
            if (nRows >= len)
                return s;
            if (nRows == 2) {
                for (i = 0; i < len; i += 2)
                    news += s.charAt(i);
                for (i = 1; i < len; i += 2)
                    news += s.charAt(i);
                return news;
            }
            for (i = 0; i < nRows; i++) {
                x = (nRows - 1) * 2 - 2 * i;
                y = 2 * i;
                if (y == 0) {
                    for (j = i; j < len; j += x)
                        news += s.charAt(j);
                } else if (x == 0) {
                    for (j = i; j < len; j += y)
                        news += s.charAt(j);
                } else {
                    news += s.charAt(i);
                    for (j = i; j < len;  j += (x + y)) {
                        if ((j + x) < len)
                            news += s.charAt(j + x);
                        if ((j + x + y) < len)
                            news += s.charAt(j + x + y);
                    }
                }
            }
            return news;
        }
    }

  • 0
    L

    Solved.
    The key point is we should use StringBuffer instead of String, which is modified.


Log in to reply
 

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