1768.交替合并字符串
给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
思路:利用双指针逐个插入即可,注意word1在前,不用关心字符串长短,简单题
代码:
class Solution { public: string mergeAlternately(string word1, string word2) { int w1 = word1.length(); int w2 = word2.length(); string res; int i = 0, j = 0; while (w1 > 0 || w2 > 0) { if (w1 > 0) res += word1[i++]; if (w2 > 0) res += word2[j++]; w1--; w2--; } return res; } };