LeetCode 5685. 交替合并字符串

给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。

返回 合并后的字符串 。

直接遍历两个字符串即可:

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int index1 = 0, index2 = 0;
        int len1 = word1.size(), len2 = word2.size();
        string ret;
        int flag = 1;
        
        while (index1 < len1 && index2 < len2) {
            if (flag) {
                ret.push_back(word1[index1]);
                ++index1;
            } else {
                ret.push_back(word2[index2]);
                ++index2;
            }
            flag = 1 - flag;
        }
        
        while (index1 < len1) {
            ret.push_back(word1[index1]);
            ++index1;
        }

        while (index2 < len2) {
            ret.push_back(word2[index2]);
            ++index2;
        }

        return ret;
    }
};
posted @ 2021-02-21 18:33  epiphanyy  阅读(8)  评论(0)    收藏  举报  来源