Skip to content

Instantly share code, notes, and snippets.

@nuxy
Created March 12, 2024 21:53
Show Gist options
  • Save nuxy/3beccaa38de6156d488e7e75f41de3be to your computer and use it in GitHub Desktop.
Save nuxy/3beccaa38de6156d488e7e75f41de3be to your computer and use it in GitHub Desktop.
LeetCode > 1768. Merge Strings Alternatively (JavaScript solution)
/**
* Merge Strings Alternatively
*
* @param {String} word1
* String of characters.
*
* @param {String} word2
* String of characters.
*
* @return {String}
*
* @see https://leetcode.com/problems/merge-strings-alternately/description/?envType=study-plan-v2&envId=leetcode-75
*/
const mergeAlternately = function(word1, word2) {
word1 = word1.split('');
word2 = word2.split('');
const len = [...word1, ...word2].length;
let str = '';
for (let i = 0; i < len; i++) {
str += (i % 2)
? word2.shift() || word1.shift()
: word1.shift() || word2.shift();
}
return str;
};
mergeAlternately('abc', 'pqr'); // apbqcr
mergeAlternately('ab', 'pqrs'); // apbqrs
mergeAlternately('abcd', 'pq'); // apbqcd
@nuxy
Copy link
Author

nuxy commented Mar 15, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment