easy and straight forward java solution


  • 0
    Z
    1. find word in string by two pointers
    2. reverse each word
    public class Solution {
        public String reverseWords(String s) {
            if (s==null || s.length()==0) return s;
            char[] arr = s.toCharArray();
            int slow = 0, fast = 0, len = s.length();
            while (fast < len) {
                while (slow<len && (slow<fast || arr[slow]==' ')) slow++;
                while (fast<len && (fast<slow || arr[fast]!=' ')) fast++;
                if (slow!=len && slow<fast) reverse(arr, slow, fast-1);
            }
            return new String(arr);
        }
        
        private void reverse(char[] arr, int i, int j) {
            while (i < j) {
                char tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i++;
                j--;
            }
        }
    }
    

Log in to reply
 

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