Home  >  Article  >  Web Front-end  >  Merge Strings Alternately in javascript

Merge Strings Alternately in javascript

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 00:53:03137browse

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 (corner case handling)
  • Using a for loop
  • Appending the final string

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn