why my Java code always exceeds the time limit?


  • 0
    R

    Here is my code, I think it is very efficient. However, the website keeps telling me that I exceed the time limit, werid...
    Anyway, please feel free to tell me anything that I can improved:

    public class Solution 
    {
        public String reverseString(String s)
     {
    
             String reverseNew="";
             
             if(s.equals(""))
             {
                 reverseNew="";
             }
             else
             {
                for (int i=s.length()-1;i>=0;i--)
                {
                    reverseNew=reverseNew+s.charAt(i);
                }
             }
    
             return reverseNew;
        }
    }
    

  • 0

    @RogerAlien Please format your code properly next time, thanks!


  • 0

    @RogerAlien A java solution:

    public class Solution 
    {
        public String reverseString(String s)
       {
            Integer len = s.length();
            StringBuilder stringBuilder = new StringBuilder(s);
            for(int i = 0; i < len/2; ++i)
            {
                char t = s.charAt(i);
                stringBuilder.setCharAt(i, s.charAt(len-i-1));
                stringBuilder.setCharAt(len-i-1, t);
            }
            return stringBuilder.toString();
        }
    }
    

Log in to reply
 

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