[LeetCode] Merge Strings Alternately
코테연습2024. 6. 27. 18:52
문제 설명
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()로 처리했어도 됐을듯.
'코테연습' 카테고리의 다른 글
[LeetCode] Greatest Common Divisor of Strings (0) | 2024.09.15 |
---|---|
[프로그래머스] 가장 많이 받은 선물 (0) | 2024.06.19 |
[프로그래머스] 옹알이 (0) | 2024.02.08 |
댓글()