力扣-1768题 交替合并字符串(C++)- 双指针

题目链接:https://leetcode.cn/problems/merge-strings-alternately/
题目如下:
力扣-1768题 交替合并字符串(C++)- 双指针_第1张图片
力扣-1768题 交替合并字符串(C++)- 双指针_第2张图片

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;
    }
};

你可能感兴趣的:(#,简单题,leetcode,c++,算法)