楼主:
yam276 ('_')
2025-05-27 18:38:461768. Merge Strings Alternately
https://leetcode.com/problems/merge-strings-alternately/
题意:
两个字串 word1, word2 让他们的字符交错组合成新字串
思路:
这一题比较简单 所以可以来挑战 Rust 链式方法
那如果你用普通的链式思路
会发现两个字串没办法轮流遍历
所以要先组合起来
用 .zip() 方法:
word1.chars().zip(word2.chars())
这样会得到一个 (word1, word2) 的 iterator
之后本来是要用 .map()
但会遇到问题 .map() 会回传 Iterator<Iterator<T>>
不符合需求 所以改用 .flat_map()
这方法会把东西压成同一个 Iterator 阵列:
.flat_map(|(c1, c2)| std::iter::once(c1).chain(std::iter::once(c2)))
用 std::iter::once() 是因为这个比较省空间
用 vec! 跟 .into_iter() 都会有额外的 heap 分配:
let i1 = std::iter::once('a'); // 更轻量
let i2 = vec!['a'].into_iter(); // 多了一层 heap 分配
我们串接完之后会遇到一个问题
就是 .zip() 会舍弃 多余的部分
所以要另外加上 word1/word2 去除对方长度的部分
做两次是因为不确定谁比较长
.chain(word1.chars().skip(word2.chars().count()))
.chain(word2.chars().skip(word1.chars().count()))
最后把展开的 Iterator 收束
.collect()
这解法空间复杂度不是最好
但是可以学链式串接用法
Code:
impl Solution {
pub fn merge_alternately(word1: String, word2: String) -> String {
word1
.chars()
.zip(word2.chars())
.flat_map(|(c1, c2)| std::iter::once(c1)
.chain(std::iter::once(c2)))
.chain(word1.chars().skip(word2.chars().count()))
.chain(word2.chars().skip(word1.chars().count()))
.collect()
}
}