2022/12/24

LeetCode 1768. Merge Strings Alternately

問題:合併字串 解法:看兩個字串長度誰比較長,判斷字串的字存在就寫入即可 JavaScript
/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
var mergeAlternately = function (word1, word2) {
    let result = "";
    const len = word2.length > word1.length ? word2.length : word1.length;
    for (let i = 0; i < len; i++) {
        if (word1[i]) {
            result += word1[i];
        }

        if (word2[i]) {
            result += word2[i];
        }
    }

    return result;
};