题目大意:输入一个以空格做为分割符的字符串,保持单词原始顺序并翻转每一个单词。性能
下面是屡次提交逐步改善代码的记录与性能数据,感谢黑化的齿轮、茶包。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) }
}
复制代码