反转句子中的单词
Reverse Words in a Sentence
开始编码给一个字符串 s。请反转单词的顺序,保留每个单词内部的字符顺序;同时去掉首尾空白,把内部多空白折叠为单空格。返回处理后的字符串。
请实现 solution(s: str) -> str。经典三步走:(1) 切分成单词列表,(2) 反转列表,(3) 用单空格重新拼接。正确的分词器是不带参数的 s.split()——这个变体按任意一段连续空白切分并丢弃空片段,一步就完成了去首尾空白和折叠多空白。然后 ' '.join(reversed(words)) 就是答案。
Examples
solution("the sky is blue") 返回 "blue is sky the"。split() 得 ["the", "sky", "is", "blue"],反转得 ["blue", "is", "sky", "the"],单空格拼接得 "blue is sky the"。
solution(" hello world ") 返回 "world hello"——首尾空白被丢,"hello" 和 "world" 之间的三空格被折叠为单空格。无论输入空白多脏,输出都是规整的。
solution("single") 返回 "single"。单词输入没有空白,切分后是单元素列表,反转还是它自己。边界:solution("") 和 solution(" ") 都返回 "",因为 "".split() 和 " ".split() 都得到空列表。
签名见 stubs/stub.py。
Practical context
把句子中单词反序,会反复出现在日志行归一化和注释文本规整这类管线里——它们的下游通常是搜索、去重和 hash-map 键索引。一个市场数据运营团队会从很多系统拿到注释文本:OMS 备注、交易所消息、券商成交确认;同一条人类含义在不同 locale 或模板下经常出现主谓宾倒装,于是要拿一段「短语指纹」做 hash-map 的键,必须先做「去首尾 + 折叠多空白」让 " filled @ 12:34 " 和 "filled @ 12:34" 碰撞到同一个键上。反转单词顺序本身则用在右到左语言渲染、RTL/LTR 混合脚本日志解析、以及微观结构里一个小技巧:把 FIX 协议自由文本字段里的单词流反过来,把最后一个 token(往往是撤单原因或 trader 标签)放到最前,方便用 tail -f | grep 追踪。Python 的 split-reverse-join 一行式是更广泛模式的锚点:只要你需要从混乱自由文本生成一个规范化键,就先做 ' '.join(text.split()) 把空白归一化,再做后续的大小写折叠、去重音、剥后缀。同样的思路在 bash 是 tr -s ' '、在 Java 是 String.join(" ", s.trim().split(\"\\\\s+\"))、在 Go 是 strings.Fields(s)——每种语言的标准库都内置了这种「按任意空白切分 + 丢空片段」的分词器,因为这一类归一化在工程里实在太常见。
约束条件
- 0 ≤ len(s) ≤ 10^4
- 字符均为 ASCII
- 空白可以包括空格、制表符和换行
- 输出无首尾空白,且单词之间恰好一个空格
- 空字符串或纯空白字符串都返回空字符串
样例
Case 1 · typical: simple sentence
输入: ["the sky is blue"]
期望: "blue is sky the"
标准用例:四个单词以单空格分隔,逆序后用单空格重新拼接,得到 "blue is sky the"。
Case 2 · typical: leading and trailing whitespace stripped
输入: [" hello world "]
期望: "world hello"
首尾空格直接丢弃。`s.split()` 不带参数时会跳过所有空白片段,所以无须显式调用 `strip()`。逆序后两词以单空格拼接。
Case 3 · typical: internal multi-whitespace collapsed
输入: ["a good example"]
期望: "example good a"
中间多空白会被 `s.split()` 折叠为单空格分隔的词列表(`["a", "good", "example"]`),逆序后输出 "example good a"。
最近提交
还没有提交记录。
编码区
实现 solution(...)。本地运行当前支持 Python 可见样例;服务端提交会运行可见样例和隐藏测试。
默认展示公开样例。点击「运行样例」后会在这里显示实际输出;点击「提交评测」会进入隐藏测试。
Case 1 · typical: simple sentence
输入: ["the sky is blue"]
期望: "blue is sky the"
标准用例:四个单词以单空格分隔,逆序后用单空格重新拼接,得到 "blue is sky the"。
Case 2 · typical: leading and trailing whitespace stripped
输入: [" hello world "]
期望: "world hello"
首尾空格直接丢弃。`s.split()` 不带参数时会跳过所有空白片段,所以无须显式调用 `strip()`。逆序后两词以单空格拼接。
Case 3 · typical: internal multi-whitespace collapsed
输入: ["a good example"]
期望: "example good a"
中间多空白会被 `s.split()` 折叠为单空格分隔的词列表(`["a", "good", "example"]`),逆序后输出 "example good a"。