Skip to content

Commit 200aae0

Browse files
committed
✨ leetcode 第 151 题。
1 parent d088ded commit 200aae0

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.fuyd.other;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* 151. 翻转字符串里的单词
8+
* 给定一个字符串,逐个翻转字符串中的每个单词。
9+
*
10+
*
11+
*
12+
* 示例 1:
13+
*
14+
* 输入: "the sky is blue"
15+
* 输出: "blue is sky the"
16+
* 示例 2:
17+
*
18+
* 输入: " hello world! "
19+
* 输出: "world! hello"
20+
* 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
21+
* 示例 3:
22+
*
23+
* 输入: "a good example"
24+
* 输出: "example good a"
25+
* 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
26+
*
27+
*
28+
* 说明:
29+
*
30+
* 无空格字符构成一个单词。
31+
* 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
32+
* 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
33+
*
34+
*
35+
* 进阶:
36+
*
37+
* 请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。
38+
*
39+
* @author fuyongde
40+
* @date 2020/3/15 21:01
41+
*/
42+
public class Solution151 {
43+
44+
public String reverseWords(String s) {
45+
String[] array = s.split(" ");
46+
List<String> list = new ArrayList<>();
47+
for (int i = array.length - 1; i >= 0; i--) {
48+
if (!array[i].equals(" ")) {
49+
list.add(array[i]);
50+
}
51+
}
52+
return String.join(" ", list);
53+
}
54+
}

0 commit comments

Comments
 (0)