leetcode刷题记录-1768. 交替合并字符串

106 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第24天,点击查看活动详情

前言

今天的题目为简单,本文采用了两个比较简单的方法进行解题,题目的难度比较低。

每日一题

今天的题目是 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

提示:

  • 1 <= word1.length, word2.length <= 100
  • word1 和 word2 由小写英文字母组成

题解

简单模拟

模拟题目的意思,先取到两个字符串中比较小的长度,然后循环遍历这个长度,将两个字符串交替拼接在一起。

然后去判断两个字符串谁比较长,将长的那一个的后面部分也拼接到答案字符串上,最后返回的就是题目所需要的答案字符串。

function mergeAlternately(word1: string, word2: string): string {
    let n = word1.length
    let m = word2.length
    let minLength = Math.min(n, m)
    let res = ''
    for (let i = 0; i < minLength; i++) {
        res += word1[i]
        res += word2[i]
    }

    if (word1[minLength]) {
        res += word1.slice(minLength, n)
    }

    if (word2[minLength]) {
        res += word2.slice(minLength, m)
    }

    return res
};

image.png

双指针

建立两个指针,分别代表当前指向的 word1 和 word2 的下标,不断地向前推进并且将下标的值加入最后的结果,这个遍历结束的条件就是两个指针都大于各自的字符串的长度,并且在遍历的过程当中,是否加入最后的结果可以使用当前的字符串这个下标是否存在值来作为判断。

function mergeAlternately(word1: string, word2: string): string {
    const m = word1.length, n = word2.length;
    let i = 0, j = 0;

    const res = [];
    while (i < m || j < n) {
        if (i < m) {
            res.push(word1[i]);
            ++i;
        }
        if (j < n) {
            res.push(word2[j]);
            ++j;
        }
    }
    return res.join('');
};

image.png