Java solution using in place XOR swap.


  • 0
    G

    Tried using XOR swap with Java, passed all tests

    public class Solution {
        public void reverseWords(char[] s) {
            for(int i=0; i < s.length/2; ++i) {
                if(s[i] != s[s.length-1-i]) {
                    s[i] ^= s[s.length-1-i];
                    s[s.length-1-i] ^= s[i];
                    s[i] ^= s[s.length-1-i];                
                }
            }
            int l = 0;
            int r = 0;
            for(int i=0; i <= s.length; ++i) {
                if(i == s.length || s[i] == ' ') {
                    r = i-1;
                    while(l < r) {
                        if(s[l] != s[r]) {
                            s[l] ^= s[r];
                            s[r] ^= s[l];
                            s[l] ^= s[r];                
                        }  
                        ++l;
                        --r;
                    }
                    l = i+1;
                }
            }
        }
    }
    

Log in to reply
 

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