Algorithm & 자료구조/알고리즘 w.JavaScript
[Leetcode] 1768.Merge Strings Alternately
프라이D
2023. 12. 18. 14:35
Merge Strings Alternately - LeetCode
Can you solve this real interview question? Merge Strings Alternately - 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 le
leetcode.com
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.
나의 풀이
const mergeAlternately = function (word1, word2) {
const totalLength = Math.max(word1.length, word2.length)
const result = [];
for(let i = 0; i < totalLength; i++) {
result.push(word1[i])
result.push(word2[i])
}
return result.join('')
};
- join 메서드를 사용하면 배열 값이 null 이거나 undefined 인 경우 빈 문자열로 치환됨
- 즉 없어짐
추가된 풀이
var mergeAlternately = function(word1, word2) {
let result = '';
for(let i = 0; i < Math.max(word1.length, word2.length); i++) {
result += word1[i] ?? '';
result += word2[i] ?? '';
}
return result;
};
- nullish 연산자를 사용해서 빈 문자열을 더해버림