File tree Expand file tree Collapse file tree 1 file changed +80
-0
lines changed Expand file tree Collapse file tree 1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 翻转字符串里的单词
2
+
3
+ 【 [ 英文练习] ( https://leetcode.com/problems/reverse-words-in-a-string/description/ ) | [ 中文练习] ( https://leetcode-cn.com/problems/reverse-words-in-a-string/description/ ) 】
4
+
5
+ ** 题目描述:** 给定一个字符串,逐个翻转字符串中的每个单词。
6
+
7
+ ** 示例:**
8
+ ```
9
+ 输入: "the sky is blue"
10
+ 输出: "blue is sky the"
11
+ ```
12
+ ** 说明:**
13
+ * 无空格字符构成一个单词。
14
+ * 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
15
+ * 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
16
+
17
+ ** 解法一:** 使用 Java API
18
+
19
+ ``` java
20
+ public String reverseWords(String s) {
21
+ // 正则式去掉空格
22
+ String [] words = s. trim(). split(" +" );
23
+ // 翻转
24
+ Collections . reverse(Arrays . asList(words));
25
+ // 单词间隔添加空格
26
+ return String . join(" " , words);
27
+ }
28
+ ```
29
+
30
+ ** 解法二:** 不使用 API ,纯裸写
31
+
32
+ ``` java
33
+ public String reverseWords(String s) {
34
+ if (s == null ) return null ;
35
+
36
+ char [] c = s. toCharArray();
37
+
38
+ // 第一步:反转整个字符串
39
+ reverse(c, 0 , c. length - 1 );
40
+ // 第二步:反转每个单词
41
+ reverseWords(c);
42
+ // 第三步:清空空格
43
+ return cleanSpaces(c);
44
+
45
+ }
46
+
47
+ // 反转所有单词
48
+ public void reverseWords(char [] c){
49
+ int i = 0 , j = 0 ;
50
+
51
+ while (i < c. length){
52
+ while (i < j || i < c. length && c[i] == ' ' ) i++ ; // 跳过空格
53
+ while (j < i || j < c. length && c[j] != ' ' ) j++ ; // 跳过非空格
54
+ reverse(c, i, j - 1 );
55
+ }
56
+ }
57
+
58
+ // 去掉头部、尾部与中间的多余空格
59
+ public String cleanSpaces(char [] c){
60
+ int i = 0 , j = 0 ;
61
+
62
+ while (j < c. length){
63
+ while (j < c. length && c[j] == ' ' ) j++ ; // 跳过空格
64
+ while (j < c. length && c[j] != ' ' ) c[i++ ] = c[j++ ]; // 去掉所有空格
65
+ while (j < c. length && c[j] == ' ' ) j++ ; // 跳过空格
66
+ if (j < c. length) c[i++ ] = ' ' ; // 仅保留一个空格
67
+ }
68
+
69
+ return new String (c). substring(0 , i);
70
+ }
71
+
72
+ // 从 i 到 j 反转数组 c
73
+ public void reverse(char [] c, int i, int j){
74
+ while (j > i){
75
+ char t = c[i];
76
+ c[i++ ] = c[j];
77
+ c[j-- ] = t;
78
+ }
79
+ }
80
+ ```
You can’t perform that action at this time.
0 commit comments