Clean and simple Java code with explanation


  • 0
    L
        public String reverseWords(String s) {
            if(s == null) {
                return null;
            }
            //Use a 2-pointers approach where keep one pointer at the space and 
            //reverse the string between current pos and the next pos.
            int slow = 0;
            int fast = 0;
            char[] arr = s.toCharArray();
            while(fast<s.length()) {
                //find the next space.
                while(fast < s.length() && s.charAt(fast)!=' ') {
                    fast++;
                }
                
                int current = fast-1;
                reverse(arr,slow,current);
                
                //find the next non-space.
                while(fast < s.length() && s.charAt(fast)==' ') {
                    fast++;
                }
                slow = fast;
            }
            return new String(arr);
        }
        
        private void reverse(char[] arr, int s, int e) {
            while(e>s) { 
                char c = arr[s];
                arr[s] = arr[e];
                arr[e] = c;
                s++;
                e--;
            }
        }
    

Log in to reply
 

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