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

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

Clarification:

  • What constitutes a word?
    • A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    • Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    • Reduce them to a single space in the reversed string.

Two pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0){return "";}
StringBuilder sb = new StringBuilder();
String[] input = s.trim().split("\\s+");
int length = input.length;

if (input.length > 0){
for (int i = length - 1; i > 0; i--){
sb.append(input[i]);
sb.append(" ");
}
sb.append(input[0]);
}

return sb.toString();
}
}

One pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0){return "";}
StringBuilder sb = new StringBuilder();
int end = s.length();

for (int i = s.length() - 1; i >= 0; i--){
if (s.charAt(i) == ' '){
if (end - i > 1){
sb.append(s.substring(i + 1, end));
sb.append(" ");
}
end = i;
}else{
if (i == 0){sb.append(s.substring(i, end));}
}
}

return sb.toString().trim();
}
}