题目
https://leetcode.cn/problems/merge-strings-alternately/?envType=study-plan-v2&envId=leetcode-75
思考
用下标i
遍历字符串word1
,下标j
遍历字符串word2
,依次加入字符串ans
,返回字符串ans
即可。
代码
class Solution {
public:
string mergeAlternately(string word1, string word2) {
string ans;
int n = word1.length();
int m = word2.length();
int i = 0, j = 0;
while (i < n || j < m) {
if (i < n) {
ans += word1[i++];
}
if (j < m) {
ans += word2[j++];
}
}
return ans;
}
};