코딩테스트 공부
[LeetCode] 1768. Merge Strings Alternately - 자바스크립트 0630
codevil
2022. 6. 30. 10:49
https://leetcode.com/problems/merge-strings-alternately/
Merge Strings Alternately - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
최대한 깔끔하게 보이게 하려고 풀이를 했다. 우선 이문제같은경우는 condition || falsy 를 사용하여 값을 가지고있는지 아닌지를 사용하는게 좋은 문제이다.
1. word1과 word2중에 길이가 더 긴 것을 구한다. 정답을 받을 result를 선언한다
const max = Math.max(word1.length, word2.length)
let result = ""
2. max를 기준으로 for문을 만들고 word1[i] || falsy가 참이면 값을 붙이고 없으면 null로 넘어가는 삼항 조건문을 word1, word2 각각 만든다.
for (let i = 0; i < max; i++) {
word1[i] || false ? result = result + word1[i] : null
word2[i] || false ? result = result + word2[i] : null
}
3. result를 return한다.
전체 풀이
var mergeAlternately = function (word1, word2) {
const max = Math.max(word1.length, word2.length)
let result = ""
for (let i = 0; i < max; i++) {
word1[i] || false ? result = result + word1[i] : null
word2[i] || false ? result = result + word2[i] : null
}
return result
};