题目链接:https://leetcode.cn/problems/merge-strings-alternately/
题目如下:
class Solution {
public:
string mergeAlternately(string word1, string word2) {
int n1=0,n2=0;
string res="";
int flag=1;
//双指针分别遍历两个字符串,用flag标记位作奇偶变换
while(word1[n1]&&word2[n2]){
if(flag==1){
res.push_back(word1[n1++]);
flag=-1;
}else{
res.push_back(word2[n2++]);
flag=1;
}
}
//将剩余的字符串添加到最后
if(n1==word1.size()&&n2<word2.size()){
while(word2[n2]) res.push_back(word2[n2++]);
}
if(n2==word2.size()&&n1<word1.size()){
while(word1[n1]) res.push_back(word1[n1++]);
}
return res;
}
};