/
_151_ReverseWordsInString.java
35 lines (32 loc) · 1.23 KB
/
_151_ReverseWordsInString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package leetcode.leetcode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* 翻转字符串里的单词
* https://leetcode-cn.com/problems/reverse-words-in-a-string/
* @author masikkk.com
* @create 2020-04-10 10:25
*/
public class _151_ReverseWordsInString {
private static class SolutionV2020 {
public String reverseWords(String s) {
if (null == s) {
return null;
}
List<String> wordsList = Arrays.asList(s.trim().split(" "));
Collections.reverse(wordsList);
return wordsList.stream().filter(word -> !word.isEmpty()).collect(Collectors.joining(" "));
}
}
public static void main(String[] args) {
SolutionV2020 solutionV2020 = new SolutionV2020();
System.out.println(solutionV2020.reverseWords("the sky is blue"));
System.out.println(solutionV2020.reverseWords(" hello world! "));
System.out.println(solutionV2020.reverseWords("a good example"));
System.out.println(solutionV2020.reverseWords(" "));
System.out.println(solutionV2020.reverseWords(""));
System.out.println(solutionV2020.reverseWords(null));
}
}