[leetcode] problem 151 – reverse words in a string

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

Example

No.1

Input: “the sky is blue”

Output: “blue is sky the”

No.2

Input: “ hello world! “

Output: “world! hello”

Explanation: Your reversed string should not contain leading or trailing spaces.

No.3

Input: “a good example”

Output: “example good a”

Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Note

  1. A word is defined as a sequence of non-space characters.

  2. Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.

  3. You need to reduce multiple spaces between two words to a single space in the reversed string.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String (String s) {
StringBuilder sb = new StringBuilder();
String[] str = s.trim().split(" ");
int index = str.length - 1;

while (index >= 0) {
if (str[index].length() > 0)
sb.append(str[index]).append(" ");

index--;
}

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