Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,

Given s = "the sky is blue",

return "blue is sky the".

Could you do it in-place without allocating extra space?

Related problem: Rotate Array

Solution:

  1. public class Solution {
  2. public void reverseWords(char[] chars) {
  3. int n = chars.length;
  4. // step 1. reverse the whole string
  5. reverse(chars, 0, n - 1);
  6. // step 2. reverse each word
  7. int i = 0, j = 0;
  8. while (i < n) {
  9. // trim the space in front
  10. while (i < n && chars[i] == ' ') { i++; }
  11. j = i;
  12. // find the border
  13. while (j < n && chars[j] != ' ') { j++; }
  14. // reverse from i to j - 1
  15. reverse(chars, i, j - 1);
  16. // continue
  17. i = j;
  18. }
  19. }
  20. private void reverse(char[] chars, int start, int end) {
  21. while (start < end) {
  22. char tmp = chars[start];
  23. chars[start] = chars[end];
  24. chars[end] = tmp;
  25. start++;
  26. end--;
  27. }
  28. }
  29. }