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
Example 3:
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
Constraints:
1 <= word1.length, word2.length <= 100
word1
and word2
consist of lowercase English letters.
class Solution {
public:
string mergeAlternately(string word1, string word2) {
string finalstr="";
int i=0,j=0;
while(i
Our purpose is to merge the two input strings. As explained in the video, we have a string a b c d and another w x y z and the resultant will be a w b x c y d z .
Let’s see the approach step by step -:
As we know, if we are using multiple conditions separated by an and or && the loop will only work when all the conditions are true. This means that when the first while loop ends there might be 2 reasons for that.
-Either both strings have no characters left un-iterated
-Or either one of them has no characters left un-iterated
If both had characters left, then the loop wouldn’t have stopped (See the condition in while).
So, we will use 2 more while loops, one will iterate on the remaining characters of word1 and the other on the remaining characters of word2. This way, only one of the while loops will be executed, if word1 has characters left then 1st while loop will run, else the second one. If none of them have characters, none of the while loop will run.
And finally we will return the resultant string (finalstr).
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India