1、交替合并字符串

原题力扣《交替合并字符串》
难度:简单
题目:给你两个字符串 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 由小写英文字母组成

解题:JS
个人:硬解

  1. 先判断这两个字符串的长度,使用长度短的来循环
  2. 根据每次循环,先拿 word1 的单次值,再拿 word2 的单次值,组合一起
  3. 当循环结束后,将长度长的剩余字符串加到组合字符串最后面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function (word1, word2) {
const len1 = word1.length;
const len2 = word2.length;

let len = Math.min(len1, len2);

let newWord = "";

for (let i = 0; i < len; i++) {
newWord += word1[i] + word2[i];
}

newWord += word1.slice(len) + word2.slice(len);

return newWord;
};

执行用时,消耗内存
66 ms,49.3 MB

耗时:12 min

官方:双指针
使用两个指针,分别指向 word1、word2,当指针小于长度时,则进行字符串添加,直到都大于长度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
var mergeAlternately = function (word1, word2) {
const len1 = word1.length;
const len2 = word2.length;

let w1 = 0;
let w2 = 0;

let newWord = "";

while(w1 < len1 || w2 < len2) {
if(w1 < len1) {
newWord += word1[w1]
w1++
}

if(w2 < len2) {
newWord += word2[w2]
w2++
}
}

return newWord;
};

执行用时,消耗内存
59 ms,49.4 MB

总结:做算法题,一定能找到对应的解法名称,如果只是硬解则只能变成死记硬背


1、交替合并字符串
https://mrhzq.github.io/职业上一二事/算法学习/每日算法/1、交替合并字符串/
作者
黄智强
发布于
2024年1月13日
许可协议