DeepSeek LeetCode 151. 反转字符串中的单词 Rust实现
·
解题思路
Rust 的 split_whitespace() 会按任意空白字符分割字符串,并自动忽略前导、尾随空格以及连续多个空格。
因此只需要:
- 用 split_whitespace() 得到所有单词
- 反转迭代器
- 用单个空格 " " 连接
代码实现
impl Solution {
pub fn reverse_words(s: String) -> String {
s.split_whitespace()
.rev()
.collect::<Vec<&str>>()
.join(" ")
}
}
如果不想显式指定 Vec<&str>,也可以写成:
impl Solution {
pub fn reverse_words(s: String) -> String {
s.split_whitespace()
.rev()
.collect::<Vec<_>>()
.join(" ")
}
}
关键点说明
要点 说明
split_whitespace() 自动处理前导、尾随、连续空格,比 split(’ ') 更简洁且正确
rev() 反转单词顺序
collect::<Vec<_>>() 将迭代器收集为 Vec<&str>,因为 join 需要切片
join(" ") 用单个空格连接单词,返回新的 String
复杂度分析
· 时间复杂度:O(n),遍历字符串一次
· 空间复杂度:O(n),存储单词列表和结果字符串
示例验证
// 输入: "the sky is blue"
// split_whitespace: ["the", "sky", "is", "blue"]
// rev: ["blue", "is", "sky", "the"]
// join: "blue is sky the"
// 输入: " hello world "
// split_whitespace: ["hello", "world"]
// rev: ["world", "hello"]
// join: "world hello"
// 输入: "a good example"
// split_whitespace: ["a", "good", "example"]
// rev: ["example", "good", "a"]
// join: "example good a"
注意:题目保证字符串只包含英文字母、数字和空格,因此 split_whitespace() 的行为完全符合要求。

更多推荐

所有评论(0)