Home > Article > Web Front-end > Merge Strings Alternately in javascript
After a long time, I'm back to solving problems in the LeetCode 75 series. Today, I solved the first problem, which was easy but had some tricky corner cases. I'd like to share how I approached this problem.
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.
Example:
Input: word1 = "abc",
word2 = "pqr"
Output: "apbqcr"
I divided my solution into three parts:
Logic check: First, I checked which word had the smallest length. I then iterated the loop based on this smallest length. If one word was longer than the other, I appended the remaining characters from the longer word to the end of the string.
Using a loop: I used a loop to alternate and merge characters from each string.
Appending the final string: Finally, I combined the strings and returned the result.
var mergeAlternately = function (word1, word2) { let str = ""; if (word2.length > word1.length) { for (let i = 0; i < word1.length; i++) { str = str + word1[i] + word2[i]; } str = str + word2.substring(word1.length); } else if (word1.length > word2.length) { for (let i = 0; i < word2.length; i++) { str = str + word1[i] + word2[i]; } str = str + word1.substring(word2.length); } else { for (let i = 0; i < word1.length; i++) { str = str + word1[i] + word2[i]; } } return str; }; console.log("result", mergeAlternately("abcd", "pq")); result: apbqcd
If you have better solutions or ideas, feel free to share with me.
The above is the detailed content of Merge Strings Alternately in javascript. For more information, please follow other related articles on the PHP Chinese website!