给你两个字符串 word1 和 word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
示例 1:
输入:word1 = “abc”, word2 = “pqr”
输出:“apbqcr”
解释:字符串合并情况如下所示:
word1: a b c
word2: p q r
合并后: a p b q c r
示例 2:
输入:word1 = “ab”, word2 = “pqrs”
输出:“apbqrs”
解释:注意,word2 比 word1 长,“rs” 需要追加到合并后字符串的末尾。
word1: a b
word2: p q r s
合并后: a p b q r s
示例 3:
输入:word1 = “abcd”, word2 = “pq”
输出:“apbqcd”
解释:注意,word1 比 word2 长,“cd” 需要追加到合并后字符串的末尾。
word1: a b c d
word2: p q
合并后: a p b q c d
提示:
1 <= word1.length, word2.length <= 100
word1 和 word2 由小写英文字母组成
思路
首先定义两个迭代器it1
和it2
,分别指向word1
和word2
的开始。然后,有一个循环,只要it1
和it2
都没有到达各自字符串的末尾,就将it1
和it2
指向的字符依次添加到word3
中,然后更新迭代器,使它们指向各自字符串的下一个字符。
当其中一个迭代器到达其字符串的末尾时,循环就会停止。然后,如果it1
没有到达word1
的末尾,就会有一个循环将it1
指向的剩余字符添加到word3
中。同样,如果it2
没有到达word2
的末尾,就会有一个循环将it2
指向的剩余字符添加到word3
中。
最后,函数返回word3
,这就是交替合并后的字符串。
AC代码
/*
* @lc app=leetcode.cn id=1768 lang=cpp
*
* [1768] 交替合并字符串
*/
// @lc code=start
class Solution {
public:
string mergeAlternately(string word1, string word2) {
string word3 = "";
auto it1 = word1.begin();
auto it2 = word2.begin();
for (; it1 != word1.end() && it2 != word2.end(); it1++, it2++) {
word3 += *it1;
word3 += *it2;
}
for (; it1 != word1.end(); it1++) {
word3 += *it1;
}
for (; it2 != word2.end(); it2++) {
word3 += *it2;
}
return word3;
}
};
// @lc code=end