Reverse Words in a String

Given an input string, reverse the string word by word.

For example,

Given s = "the sky is blue",

return "blue is sky the".

Solution:

  1. public class Solution {
  2. public String reverseWords(String s) {
  3. if (s == null) return null;
  4. char[] a = s.toCharArray();
  5. int n = a.length;
  6. // step 1. reverse the whole string
  7. reverse(a, 0, n - 1);
  8. // step 2. reverse each word
  9. reverseWords(a, n);
  10. // step 3. clean multiple spaces
  11. return cleanSpaces(a, n);
  12. }
  13. void reverseWords(char[] a, int n) {
  14. int i = 0, j = 0;
  15. while (i < n) {
  16. while (i < j || i < n && a[i] == ' ') i++; // skip spaces
  17. while (j < i || j < n && a[j] != ' ') j++; // skip non spaces
  18. reverse(a, i, j - 1); // reverse the word
  19. }
  20. }
  21. // trim leading, trailing and multiple spaces
  22. String cleanSpaces(char[] a, int n) {
  23. int i = 0, j = 0;
  24. while (j < n) {
  25. while (j < n && a[j] == ' ') j++; // skip spaces
  26. while (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces
  27. while (j < n && a[j] == ' ') j++; // skip spaces
  28. if (j < n) a[i++] = ' '; // keep only one space
  29. }
  30. return new String(a).substring(0, i);
  31. }
  32. // reverse a[] from a[i] to a[j]
  33. private void reverse(char[] a, int i, int j) {
  34. while (i < j) {
  35. char t = a[i];
  36. a[i++] = a[j];
  37. a[j--] = t;
  38. }
  39. }
  40. }