題目大意:輸入一個以空格做爲分割符的字符串,保持單詞原始順序並翻轉每一個單詞。性能
下面是屢次提交逐步改善代碼的記錄與性能數據,感謝黑化的齒輪、茶包。ui
最樸素的提交spa
pub fn reverse_words(s: String) -> String {
let mut substrings: Vec<&str> = s.split(' ').collect();
let mut res = String::new();
substrings
.iter()
.map(|&s| {
let bytes = unsafe { s.as_bytes() };
let mut bytes = Vec::from(bytes);
bytes.reverse();
unsafe { String::from_utf8_unchecked(bytes) }
})
.fold(&mut res, |res, s| {
res.push_str(s.as_str());
res.push_str(" ");
res
});
let _ = res.pop();
res
}
複製代碼
使用了move語義。內存佔用沒降低。code
pub fn reverse_words(s: String) -> String {
let mut substrings: Vec<&str> = s.split(' ').collect();
let mut res = String::new();
substrings
.into_iter() // move語義
.map(|s| {
let bytes = unsafe { s.as_bytes() };
let mut bytes = Vec::from(bytes);
bytes.reverse();
unsafe { String::from_utf8_unchecked(bytes) }
})
.fold(&mut res, |res, s| {
res.push_str(s.as_str());
res.push_str(" ");
res
});
let _ = res.pop();
res
}
複製代碼
代碼簡化:利用Slice::join
替代fold()
。cdn
pub fn reverse_words(s: String) -> String {
let mut strings: Vec<&str> = s.split(' ').collect();
strings
.into_iter()
.map(|s| {
let bytes = unsafe { s.as_bytes() };
let mut bytes = Vec::from(bytes);
bytes.reverse();
unsafe { String::from_utf8_unchecked(bytes) }
})
.collect::<Vec<_>>()
.join(" ")
}
複製代碼
代碼簡化:利用迭代器rec()
替代Vec::reverse()
。blog
pub fn reverse_words(s: String) -> String {
let mut strings: Vec<&str> = s.split(' ').collect();
strings
.into_iter()
.map(|s| {
let byte_chars = s.bytes().rev().collect::<Vec<_>>();
unsafe { String::from_utf8_unchecked(byte_chars) }
})
.collect::<Vec<_>>()
.join(" ")
}
複製代碼
代碼簡化:map()
內部合併成一條語句。內存
pub fn reverse_words(s: String) -> String {
s.split(' ')
.collect::<Vec<&str>>()
.into_iter()
.map(|s| unsafe { String::from_utf8_unchecked(s.bytes().rev().collect::<Vec<_>>()) })
.collect::<Vec<_>>()
.join(" ")
}
複製代碼
算法簡化:利用split_mut()
原地翻轉。leetcode
pub fn reverse_words(s: String) -> String {
let mut s = s.into_bytes();
for c in s.split_mut(|&c| c == b' ') {
c.reverse();
}
unsafe { String::from_utf8_unchecked(s) }
}
複製代碼
代碼簡化:利用for_each
適配器。字符串
pub fn reverse_words(s: String) -> String {
let mut s = s.into_bytes();
s.split_mut(|&c| c == b' ').for_each(|s| s.reverse());
unsafe { String::from_utf8_unchecked(s) }
}
複製代碼