Easy to understand Java solution with comments


  • 0
    W
    public class Solution {
        public String reverseWords(String s) {
            // trim and remove whitespace between words
            char[] c = s.trim().replaceAll("\\s+"," ").toCharArray(); 
            reverse(c, 0, c.length - 1); // first reverse entire string
            for (int i = 0, j = 0; i <= c.length; i++) {
                if (i == c.length || c[i] == ' ') { // if i is ' ' or last
                    reverse(c, j, i - 1); // j is start of word, i - 1 is end
                    j = i + 1; // update j to be start of next word
                }
            }
         	    return new String(c);
        }
    
        // standard in place reverse function
        public void reverse(char[] s, int start, int end) {
            while (start < end) {
                char temp = s[start];
                s[start] = s[end];
                s[end] = temp;
                start++;
                end--;
            }
        }
    }
    

    Output after each iteration would be something like this:
    "the sky is blue"
    "eulb si yks eht"
    "blue si yks eht"
    "blue is yks eht"
    "blue is sky eht"
    "blue is sky the"


Log in to reply
 

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