C++小白修仙记_LeetCode刷题_1768交替合并字符串

1768. 交替合并字符串

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

返回 合并后的字符串 。

示例:

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

方法一:

时间复杂度O(N) 空间复杂度O(N)

class Solution {
public:
    string mergeAlternately(string word1, string word2) { 
        string result;//创建结果空字符串
        int len1 = word1.length();
        int len2 = word2.length();//记录word1 word2字符串长度
        int i = 0;
        int j = 0;//i j随len1 len2大小 遍历字符串

        while( i < len1 && j < len2)//先将word1 word2相同长度的部分依次加入到result
        {
            result += word1[i++];
            result += word2[j++];
        }
        //短的字符后串长度为开始 开始遍历剩余字符串 加到result
        //第一种情况: len1 > len2
        while( i < len1 )
        {
            result += word1[i++];
        }

        //第二种情况:len1 < len2
        while( j < len2)
        {
            result += word2[j++];
        }

        return result;
    }
};

方法二:

时间复杂度O(N) 空间复杂度O(N)

class Solution {
public:
    string mergeAlternately(string word1, string word2) { 
        string result;//创建结果空字符串
        int len1 = word1.length();
        int len2 = word2.length();//记录word1 word2字符串长度
        for(int i = 0; i < len1 || i < len2; i++)
        {//先判断如果i小于len1,则将word1的第i个字符添加到result中
            if(i < len1)
            {
                result += word1[i];
            }
         //再判断如果i小于len2,则将word2的第i个字符添加到result中
            if(i < len2)
            {
                result += word2[i];
            }
        }
        return result;
    }
};
posted @ 2025-07-30 13:06  Jaylan  阅读(11)  评论(0)    收藏  举报