3ms Java solution


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

  • 1

    pulling you temp variable out of the for loop can reduce the time to 2ms, like my code as follows, because temp is a temporary variable it is unnecessarily declared so many times:

    public String reverseString(String s) {
    	char[] charArray = s.toCharArray();
    	char temp;
    	int len = charArray.length;
    	for (int idx = 0; idx < len / 2; idx++) {
    		temp = charArray[idx];
    		charArray[idx] = charArray[len - idx - 1];
    		charArray[len - idx - 1] = temp;
    	}
    	return new String(charArray);
    }
    

Log in to reply
 

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