Time Limit Exceeded????


  • -1
    M
    This post is deleted!

  • 2
    J

    Java String is immutable, so by "re += c[i];", you are creating a new String object each time. Creating objects costs time, but what is worse is that when there are too many small objects which are no longer used, garbage collector starts to work, and this slows down the program. I guess this is the reason that your program exceeded time limit.

    Try

    public class Solution {
        public String reverseString(String s) {
            if (s == null || s.length() == 0)
            {
                return "";
            }
            char[] reverse = new char[s.length()];
            for (int i = s.length() - 1; i >= 0; i--)
            {
                reverse[s.length() - 1 - i] = s.charAt(i);
            }
            return new String(reverse);
        }
    }
    

    It used a char array to reverse the letters, and only converted the char array to String at the end to avoid creating String objects when a letter is added each time.


  • 0

    Interesting theory, but I don't think that's it. I added String t = "" + i; to your loop, which creates a new string each iteration and does slow down your time from 4ms to 20ms, still well within the allowed time.

    But you're close to the correct reason.


Log in to reply
 

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