leetbook_ioa/docs/LCR 181. 字符串中的单词反转.md
下图中的
s对应本题的message。
<,,,,,,,,,,,,,,,,,>
class Solution:
def reverseMessage(self, message: str) -> str:
message = message.strip() # 删除首尾空格
i = j = len(message) - 1
res = []
while i >= 0:
while i >= 0 and message[i] != ' ': i -= 1 # 搜索首个空格
res.append(message[i + 1: j + 1]) # 添加单词
while i >= 0 and message[i] == ' ': i -= 1 # 跳过单词间空格
j = i # j 指向下个单词的尾字符
return ' '.join(res) # 拼接并返回
class Solution {
public String reverseMessage(String message) {
message = message.trim(); // 删除首尾空格
int j = message.length() - 1, i = j;
StringBuilder res = new StringBuilder();
while (i >= 0) {
while (i >= 0 && message.charAt(i) != ' ') i--; // 搜索首个空格
res.append(message.substring(i + 1, j + 1) + " "); // 添加单词
while (i >= 0 && message.charAt(i) == ' ') i--; // 跳过单词间空格
j = i; // j 指向下个单词的尾字符
}
return res.toString().trim(); // 转化为字符串并返回
}
}
利用 “字符串分割”、“列表倒序” 的内置函数 (面试时不建议使用) ,可简便地实现本题的字符串翻转要求。
{:align=center width=500}
"" )。解决方法:倒序遍历单词列表,并将单词逐个添加至 StringBuilder ,遇到空单词时跳过。{:align=center width=500}
class Solution:
def reverseMessage(self, message: str) -> str:
message = message.strip() # 删除首尾空格
strs = message.split() # 分割字符串
strs.reverse() # 翻转单词列表
return ' '.join(strs) # 拼接为字符串并返回
class Solution {
public String reverseMessage(String message) {
String[] strs = message.trim().split(" "); // 删除首尾空格,分割字符串
StringBuilder res = new StringBuilder();
for (int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
if(strs[i].equals("")) continue; // 遇到空单词则跳过
res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
}
return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
}
}
Python 可一行实现:
class Solution:
def reverseMessage(self, message: str) -> str:
return ' '.join(message.strip().split()[::-1])
split() 方法: 为 $O(N)$ ;trim() 和 strip() 方法: 最差情况下(当字符串全为空格时),为 $O(N)$ ;join() 方法: 为 $O(N)$ ;reverse() 方法: 为 $O(N)$ ;