需求来源于实际的工作场景。后发现在 Leetcode 上面也有这样的题目,我个人不喜欢 Leetcode,但是既然有了也方便提供题目描述,于是就干脆记录一下。
本身算法不复杂,属于 Easy 级别的题目。算是当成一个自己的小抄吧。
题目描述 英文题源:点我 : Leetcode-1768
中文题源:点我 : Leetcode-1768
题目描述:
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。 如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。返回合并后的字符串
示例 1:
输入:word1 = " abc" , word2 = " pqr"
输出:" apbqcr"
解释:字符串合并情况如下所示:
word1: a b c
word2: p q r
合并后: a p b q c r
示例 2:
输入:word1 = " ab" , word2 = " pqrs"
输出:" apbqrs"
解释:注意,word2 比 word1 长," rs" 需要追加到合并后字符串的末尾。
word1: a b
word2: p q r s
合并后: a p b q r s
示例 3:
输入:word1 = " abcd" , word2 = " pq"
输出:" apbqcd"
解释:注意,word1 比 word2 长," cd" 需要追加到合并后字符串的末尾。
word1: a b c d
word2: p q
合并后: a p b q c d
题目解法 本质上思路比较简单,就不再赘述。直接贴代码:
fn main ( ) {
assert_eq! (
" a1b2c3def" ,
merge_alternately ( " abcdef" . to_string ( ) , " 123" . to_string ( ) )
) ;
assert_eq! (
" a1b2c3456" ,
merge_alternately ( " abc" . to_string ( ) , " 123456" . to_string ( ) )
) ;
}
pub fn merge_alternately ( word1 : String, word2 : String) -> String {
let mut ans = String :: new( ) ;
let mut i = 0 ;
let mut j = 0 ;
while i < word1. len ( ) || j < word2. len ( ) {
if let Some ( c) = word1. chars ( ) . nth ( i) {
ans. push ( c) ;
}
if let Some ( c) = word2. chars ( ) . nth ( i) {
ans. push ( c) ;
}
i += 1 ;
j += 1 ;
}
ans
}
后续更新 20210520 更新: 后来又意外发现了一个 crate 名为 itertools 的库,它可以替我们做很多事情。
比如 merge 操作、带 ordering 的 merge 操作,笛卡尔积 product 操作,以及本文涉及的 interleave 操作。
那么有了 itertools 的辅助,即可短暂地实现 interleave 的操作。
代码如下:
use itertools:: Itertools;
fn main ( ) {
assert_eq! (
" a1b2c3def" ,
merge_alternately_itertools ( " abcdef" . to_string ( ) , " 123" . to_string ( ) )
) ;
assert_eq! (
" a1b2c3456" ,
merge_alternately_itertools ( " abc" . to_string ( ) , " 123456" . to_string ( ) )
) ;
}
pub fn merge_alternately_itertools ( word1 : String, word2 : String) -> String {
let mut ans = String :: new( ) ;
ans = word1. chars ( ) . interleave ( word2. chars ( ) ) . collect ( ) ;
ans
}
上一页 → Rust版Basic Calculator II以及改进