[LeetCode] Merge Strings Alternately

1768. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string mergeAlternately(string word1, string word2) {
stringstream ss;
int len = max(word1.length(), word2.length());
for(int i = 0; i < len; i++) {
if(i < word1.length())
ss<<word1[i];
if(i < word2.length())
ss<<word2[i];
}

return ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/21/PS/LeetCode/merge-strings-alternately/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.