1768. 交替合并字符串

交替合并字符串

题干:

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

提示:

  • 1 <= word1.length, word2.length <= 100
  • word1word2 由小写英文字母组成

示例:

输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1:  a   b   c
word2:    p   q   r
合并后:  a p b q c r

题解:

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int len1 = word1.length(), len2 = word2.length();
        string res;
        int i = 0;
        while(i < len1 || i < len2) {
            if(i < len1) {
                res += word1[i];
            }
            if(i < len2) {
                res += word2[i];
            }
            i++;
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode每日一题,leetcode,算法)