Java:

1
2
3
4
5
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
Collections.reverse(Arrays.asList(words));
return String.join(" ", words);
}

  1. list才是Collections的一种,才能用reverse;
  2. String.join();

Python: easier:

1
return " ".join(s.strip().split()[::-1])