Skip to content

Commit bb3c9ff

Browse files
committed
151.颠倒字符串中的单词,双指针,双端队列
1 parent c46f002 commit bb3c9ff

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
145. 二叉树的后序遍历
6464
146. LRU 缓存
6565
148. 排序链表
66+
151. 颠倒字符串中的单词
6667
152. 乘积最大子数组
6768
155. 最小栈
6869
160. 相交链表

leetcode_Java/Solution0151.java

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// 151. 颠倒字符串中的单词
2+
3+
4+
/*
5+
1、字符串去掉头尾空格,按空格分隔字符串,倒序拼接单词
6+
2、拼接单词字符串可以使用StringBuilder直接构造,也可以先把单词加到列表最后拼接
7+
*/
8+
class Solution {
9+
public String reverseWords(String s) {
10+
String[] splits = s.trim().split(" ");
11+
StringBuilder res = new StringBuilder();
12+
for (int i = splits.length - 1; i >= 0; i--) {
13+
String word = splits[i];
14+
if (word == "") {
15+
continue;
16+
}
17+
res.append(word);
18+
if (i > 0) {
19+
res.append(" ");
20+
}
21+
}
22+
return res.toString();
23+
}
24+
}
25+
26+
27+
/*
28+
去掉头尾空格,正则表达式\\s+ 连续空白字符作为分隔符,得到单词列表,列表反转,再通过空格字符连接成字符串
29+
*/
30+
class Solution {
31+
public String reverseWords(String s) {
32+
s = s.trim();
33+
List<String> list = Arrays.asList(s.split("\\s+"));
34+
Collections.reverse(list);
35+
return String.join(" ", list);
36+
}
37+
}
38+
39+
40+
/*
41+
双指针:从右到左,跳过空格,遍历得到一个单词的索引区间,将单词加入列表,最后列表通过空格字符连接成字符串
42+
*/
43+
class Solution {
44+
public String reverseWords(String s) {
45+
s = s.trim();
46+
int n = s.length();
47+
int left = n - 1, right = n - 1;
48+
List<String> list = new ArrayList<>();
49+
while (left >= 0) {
50+
while (left >= 0 && s.charAt(left) != ' ') {
51+
left--;
52+
}
53+
list.add(s.substring(left + 1, right + 1));
54+
while (left >= 0 && s.charAt(left) == ' ') {
55+
left--;
56+
}
57+
right = left;
58+
}
59+
return String.join(" ", list);
60+
}
61+
}
62+
63+
64+
/*
65+
双端队列:从左到右,遍历字符构造出一个单词,遇到空格时且单词不为空就将单词加到队列头部,最后队列通过空格字符连接成字符串
66+
*/
67+
class Solution {
68+
public String reverseWords(String s) {
69+
s = s.trim();
70+
s += " ";
71+
int n = s.length();
72+
int left = 0, right = n - 1;
73+
Deque<String> queue = new ArrayDeque<>();
74+
StringBuilder word = new StringBuilder();
75+
while (left <= right) {
76+
char c = s.charAt(left);
77+
if (word.length() != 0 && c == ' ') {
78+
queue.offerFirst(word.toString());
79+
word.setLength(0);
80+
} else if (c != ' ') {
81+
word.append(s.charAt(left));
82+
}
83+
left++;
84+
}
85+
return String.join(" ", queue);
86+
}
87+
}

0 commit comments

Comments
 (0)