LeetCode: Merge Strings Alternately

쭌로그·3일 전

LeetCode

풀이

  1. Math.max를 통해 2개의 문자열 중 긴 길이를 찾는다.
  2. for문을 탐색하며 해당 문자의 i번째 인덱스가 undefined가 아니라면 answer 배열에 push
  3. answer.join()한 결과값을 리턴
/**
 * @param {string} word1
 * @param {string} word2
 * @return {string}
 */
var mergeAlternately = function(word1, word2) {
    const maxLen = Math.max(word1.length, word2.length);

    let answer = [];

    for(let i=0;i<maxLen;i++) {
        if(word1[i]!== undefined) answer.push(word1[i]);

        if(word2[i]!== undefined) answer.push(word2[i]);
    }

    return answer.join('')
};
profile
매일 발전하는 프론트엔드 개발자

0개의 댓글