2ms Java solution


  • 7
    S
    public class Solution {
        public String reverseString(String s) {
            if(s == null) return null;
            if(s.equals("")) return s;
            char[] arrChar = s.toCharArray();
            for (int i = 0, j = arrChar.length-1; i <= j; i++, j--) {
                char temp = arrChar[i];
                arrChar[i] = arrChar[j];
                arrChar[j] = temp;
            }
            return new String(arrChar);
        }
    }

  • 0
    F

    this is my answer:

    public class Solution {
        public String reverseString(String s) {
            
            char array[] = s.toCharArray();
            char c;
            for(int i=0;i<s.length()/2;i++)
            {
                c=array[i];
                array[i]=array[s.length()-i-1];
                array[s.length()-i-1]=c;
            }
            return new String(array);
        }
    }
    

    but it used 4ms.Could yout tell me why? thanks.


  • 0
    F

    I changed the "s.length()" to "array.length".The time changed into 3ms.


  • 0
    J

    @flpanbin maybe you can use j=array.length,and then array[i]=array[j-i-1];array[j-i-1]=c;
    it only calculate array.length for once.


  • 0
    F

    @j1ml3e thanks a lot .I got it!


  • 0
    W

    thanks a lot!


  • 0
    R

    @Shans.Xia Few suggestions:

    Instead of

    if(s == null) return null;
    if(s.equals("")) return s;    
    

    you can do

    if(s == null || s.length() < 2) return s;
    

    The for loop condition can be i < j. '=' is redundant


Log in to reply
 

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