[LeetCode] Merge Strings Alternately

코테연습|2024. 6. 27. 18:52

https://leetcode.com/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75

 

문제 설명

You are given two strings word1 and word2. 

Merge the strings by adding letters in alternating order, starting with word1. 

If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.

Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd" 

Constraints:
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.

 

풀이

주어진 단어 두 개에서 각각 한 철자씩 교대로 배치한 문자열을 리턴하는 문제.

첫 번째 매개변수로 주어진 단어 속 철자부터 앞에 배치된다.

/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
const mergeAlternately = function(word1, word2) {
    let answer = "";
    const wordLength = word1.length > word2.length ? word1.length : word2.length;
    for(let i=0; i < wordLength; i++){
        answer += word1[i] ?? ""
        answer += word2[i] ?? ""
    }
    return answer;
};

 

wordLength는 그냥 Math.max()로 처리했어도 됐을듯.

댓글()