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.
Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r
Example 2:
1 2 3 4 5 6
Input: word1 = "ab", word2 = "pqrs" Output: "apbqrs" Explanation: Notice that as word2 is longer, "rs" is appended to the end. word1: a b word2: p q r s merged: a p b q r s
Example 3:
1 2 3 4 5 6
Input: word1 = "abcd", word2 = "pq" Output: "apbqcd" Explanation: Notice that as word1 is longer, "cd" is appended to the end. word1: a b c d word2: p q merged: a p b q c d
Solution - JavaScript
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var mergeAlternately = function(word1, word2) { let result = ""; let i = 0; let j = 0; while (i < word1.length && j < word2.length) { result += word1[i] + word2[j]; i++; j++; } while (i < word1.length) { result += word1[i]; i++; } while (j < word2.length) { result += word2[j]; j++; } return result; };
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var mergeAlternately = function(word1, word2) { let result = ""; if (word1.length > word2.length) { for (let i = 0; i < word2.length; i++) { result += word1[i] + word2[i]; } result += word1.slice(word2.length); } else { for (let i = 0; i < word1.length; i++) { result += word1[i] + word2[i]; } result += word2.slice(word1.length); } return result; };
Solution - Ruby
Solution 1:
1 2 3 4 5 6 7 8 9 10 11
defmerge_alternately(word1, word2) i, j = 0, 0 result = "" while i < word1.length || j < word2.length result += word1[i] if i < word1.length result += word2[j] if j < word2.length i += 1 j += 1 end result end
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# @param {String} word1 # @param {String} word2 # @return {String} defmerge_alternately(word1, word2) result = "" if word1.length > word2.length for i in0..word2.length-1 result += word1[i] + word2[i] end result += word1[word2.length..-1] else for i in0..word1.length-1 result += word1[i] + word2[i] end result += word2[word1.length..-1] end return result end
defmergeAlternately(self, word1: str, word2: str) -> str: result = "" i = 0 j = 0 while i < len(word1) and j < len(word2): result += word1[i] + word2[j] i += 1 j += 1 if i < len(word1): result += word1[i:] if j < len(word2): result += word2[j:] return result
Solution 2:
1 2 3 4 5 6 7 8 9 10 11
defmergeAlternately(self, word1: str, word2: str) -> str: result = "" iflen(word1) > len(word2): for i inrange(len(word2)): result += word1[i] + word2[i] result += word1[len(word2):] else: for i inrange(len(word1)): result += word1[i] + word2[i] result += word2[len(word1):] return result