持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 13 天,点击查看活动详情。
交替合并字符串
原题地址
给你两个字符串 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
提示:
1 <= word1.length, word2.length <= 100- word1 和 word2 由小写英文字母组成
思路分析
- 按照题目要求,需要
word1和word2交替合并,并且将多出来的字符串追加到最后字符串的结尾; - 首先,得到
word1和word2长度的最小值,按照这个长度来循环交替; - 然后,得到
word1和word2除去最小长度后的字符串,此处使用substring方法,方便后面进行追加; - 再然后,以
len为最大值,遍历word1和word2,给最小长度内的字符进行交替叠加; - 循环结束后,将去除后的字符串追加到结果字符串
res中; - 最后返回
res即可。
AC 代码
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function(word1, word2) {
const len = Math.min(word1.length, word2.length)
const str1 = word1.substring(len)
const str2 = word2.substring(len)
let res = ''
for(let i = 0; i < len; i++) {
res += `${word1[i]}${word2[i]}`
}
res += `${str1}${str2}`
return res
};
结果:
- 执行结果: 通过
- 执行用时:72 ms, 在所有 JavaScript 提交中击败了12.35%的用户
- 内存消耗:40.9 MB, 在所有 JavaScript 提交中击败了97.65%的用户
- 通过测试用例:108 / 108