Last active
July 12, 2023 06:08
-
-
Save mtzfox/513f015547fb09b53eee844bd8255b07 to your computer and use it in GitHub Desktop.
Merge two strings with alternating letters: abc, xyz => axbycz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mergeAlternately(word1, word2) { | |
// get max length of each word | |
let m = word1.length, | |
n = word2.length, | |
// starting word | |
result = ''; | |
// if either index is less than word length, add current letter to result | |
for (i = 0; i < Math.max(m, n); i++) { | |
if (i < m) { | |
result += word1[i]; | |
} | |
if (i < n) { | |
result += word2[i]; | |
} | |
} | |
return result; | |
} | |
mergeAlternately('abc', 'xyz'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mergeAlternately(word1, word2) { | |
// get max length of each word | |
let m = word1.length, | |
n = word2.length, | |
// starting word and indices | |
result = '', | |
i = 0, | |
j = 0; | |
// if either index is less than word length, | |
// add current letter to result then add to that index | |
while (i < m || j < n) { | |
if (i < m) { | |
result += word1[i]; | |
i++; | |
} | |
if (j < n) { | |
result += word2[j]; | |
j++; | |
} | |
} | |
return result; | |
} | |
mergeAlternately('abc', 'xyz'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leetcode 1768. Merge Strings Alternately
Thought process