Java solution beats over 90% of current solutions


  • 0
    H

    Simple solution reversing one word at a time when a space is encountered, and using the last index of the array (arr.length-1) to perform the last reversal.

    public class Solution {
        public String reverseWords(String s) {
            char[] arr = s.toCharArray();
            int index = 0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == ' ' || i == arr.length-1) {
                    reverseWord(arr, index, i != arr.length-1 ? i-1 : i);
                    index = i+1;
                }
            }
            return new String(arr);
        }
        
        public void reverseWord(char[] arr, int start, int end) {
            while (start < end) {
                char temp = arr[start];
                arr[start++] = arr[end];
                arr[end--] = temp;
            }
        }
    }
    

Log in to reply
 

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