1768. Merge Strings Alternately

Leetcode link

题目简介

/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */

题目给我们两个字符串,要求我们返回一个新的字符串,字符串的字符由两个旧字符串字符交替排列(word1 先)

解题思路

使用两个指针分别指向两个旧字符串,然后依序取字符放入新字符串即可

Javascript

/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
var mergeAlternately = function (word1, word2) {
    let res = ''
    let idx1 = 0
    let idx2 = 0
    const len1 = word1.length
    const len2 = word2.length

    while (idx1 < len1 || idx2 < len2) {
        if(idx1 < len1) {
            res += word1[idx1]
        }
        if(idx2 < len2) {
            res += word2[idx2]
        }
        idx1++
        idx2++
    }

    return res
};

results matching ""

    No results matching ""