[Java] LeetCode has strange evaluation application


  • 1
    V

    I don't understand why one solution is better than another

    Solution 1

        public String reverseString(String s) {
            final char[] chars = new char[s.length()];
    		for (int i = s.length() - 1, j = 0; i > -1; i--, j++){
    			chars[j] = s.charAt(i);
    		}
    		return new String(chars);
        }
    

    Will take time O(n)

    Solution 2

     public static String reverseString1(final String s) {
    		final char[] str = s.toCharArray();
    		int begin = 0;
    		int end = s.length() - 1;
    		while (begin < end) {
    			str[begin] = (char) (str[begin] ^ str[end]);
    			str[end] = (char) (str[begin] ^ str[end]);
    			str[begin] = (char) (str[end] ^ str[begin]);
    			begin++;
    			end--;
    		}
    		return new String(str);
    	}
    

    I was analysing current solution in such way

    class String
    
    public char[] toCharArray() {
            char result[] = new char[value.length];
            System.arraycopy(value, 0, result, 0, value.length);
            return result;
        }
    

    copying existing array so as for me it is O(n), than reversing chars on created array that is also O(n) as result we get O(2n)

    Local environment testing
    Local tests shows that solution 1 is better than solution 2

    Leetcode perfomance testing
    Shows that solution 2 is better than solution 1


  • 0
    K

    Hi,
    Could you please tell me the meaning of those codes:

    str[begin] = (char) (str[begin] ^ str[end]);
    str[end] = (char) (str[begin] ^ str[end]);
    str[begin] = (char) (str[end] ^ str[begin]);
    

    I am a fresh, It's too hard to me.

    Thanks very much!


  • 0
    V

    @Kexin_Li
    So we need to swap str[begin] and str[end]
    So there are 2 solutions

    char tempChar = str[begin];
    str[begin] = str[end] ;
    str[end] = tempChar;
    

    And second solution that you mention but without using temporary variable ,folk said that it is more efficient.


  • 0
    K

    @vova-rova-gmail-com I think I got it! Thank you very much!


Log in to reply
 

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