Readable Java solution


  • 0
    F
    class Solution {
        public String reverseWords(String s) {
            return reverseWords(s.split(" "));
        }
        
        private String reverseWords(String[] words) {
            String result = "";
            
            for (String word : words) {
                result += reverse(word) + " ";
            }
            
            // There is going to be a trailing space at the end, so use trim
            return result.trim();
        }
        
        private String reverse(String word) {
            char[] letters = word.toCharArray();
            int i = 0;
            int j = letters.length - 1;
            
            while (i < j) {
                swap(letters, i, j);
                i++;
                j--;
            }
            return new String(letters);
        }
        
        private void swap(char[] word, int i, int j) {
            char t = word[j];
            word[j] = word[i];
            word[i] = t;
        }
    }
    

Log in to reply
 

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