151. Reverse Words in a String
https://leetcode.com/problems/reverse-words-in-a-string/
題意:
反轉字串的單字順序並刪除多餘的空白
思路:
題目有小挑戰 但 Rust 用 in-place 太難了
用一般的超簡單 因為一堆內建 function
Code:
impl Solution {
pub fn reverse_words(s: String) -> String {
s.split_whitespace().rev().collect::<Vec<_>>().join(" ")
}
}
s -> 用空格當分隔蒐集單字 -> 反轉 Iterators 順序 -> 壓成 Vec -> 用空格展開
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.48.170 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1749102066.A.A89.html