ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

DeepSeek LeetCode 151. 反转字符串中的单词 Rust实现

DeepSeek    LeetCode 151. 反转字符串中的单词  Rust实现 解题思路Rust 的 split_whitespace() 会按任意空白字符分割字符串并自动忽略前导、尾随空格以及连续多个空格。因此只需要用 split_whitespace() 得到所有单词反转迭代器用单个空格 连接代码实现implSolution{pubfnreverse_words(s:String)-String{s.split_whitespace().rev().collect::Vecstr().join( )}}如果不想显式指定 Vecstr也可以写成implSolution{pubfnreverse_words(s:String)-String{s.split_whitespace().rev().collect::Vec_().join( )}}关键点说明要点 说明split_whitespace() 自动处理前导、尾随、连续空格比 split(’ ) 更简洁且正确rev() 反转单词顺序collect::Vec_() 将迭代器收集为 Vecstr因为 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() 的行为完全符合要求。
返回列表