Swap the header and the tail. Java solution


  • 0
    M

    First, Split the string into an array by space delimiter. then swap the header and tail in a loop.

        public static String reverseWords(String s) {
            if (s == null || s.trim().length() == 0) {
                return "";
            }
            String[] arr = s.trim().split("\\s+");
            if (arr.length == 1) {
                return arr[0];
            }
    
            int mid = arr.length / 2;
            for (int i = 0; i < mid; i++) {
                // swap i and arr.len-i-1
                String temp = arr[i];
                arr[i] = arr[arr.length - i - 1];
                arr[arr.length - i - 1] = temp;
            }
            return String.join(" ", arr);
        }
    

Log in to reply
 

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