Merge Strings Alternately

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.

Return the merged string.

Example 1:

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:

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

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string mergeAlternately(string word1string word2)
{

    string res = "";
    for (int i = 0i < min(word1.size(), word2.size()); i++)
    {
        res += word1[i];
        res += word2[i];
    }
    if (word1.size() > word2.size())
        res += word1.substr(word2.size());

    if (word1.size() < word2.size())
        res += word2.substr(word1.size());

    return res;
}

int main()
{
    string word1 = "abc"word2 = "pqr";

    cout << mergeAlternately(word1word2<< "\n";

    return 0;
}


No comments:

Post a Comment