力扣1768(C&python)--交替合并字符串

力扣1768(C&python)–交替合并字符串

1768.交替合并字符串

给你两个字符串 word1word2 。请你从 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 由小写英文字母组成

##C++实现

class Solution
{
public:
    string mergeAlternately(string word1, string word2)
    {
        int m = word1.size();
        int n = word2.size();
        int Min = min(m, n);
        // for(int i=0;i<n;i+)
        int i;
        string res="";
        for ( i = 0; i < Min; i++)
        {
            res += word1[i] ;
            res += word2[i];
        }
        int rest = abs(m - n);//求整数的绝对值
        if (m > n)
        {
            for (; i < m; i++)
            {
                res += word1[i];
            }
        }
        else if (n>m)
        {
            for (; i < n; i++)
            {
                res += word2[i];
            }
        }return res;
    }
} ;

##C++实现2

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int n = word1.size(), m = word2.size(), i = 0;
        string ans;
        for(i=0; i<n && i<m; i++)//如果i小于m和n的最小值,那么可以写成i<m&&i<n;
        {
            ans += word1[i];
            ans += word2[i];
        }
        
        while(i < n) ans += word1[i++];
        while(i < m) ans += word2[i++];
        return ans;
    }
};

以上参考博客https://blog.csdn.net/weixin_45929885/article/details/114069076

##python实现

 1 class Solution:
 2     def mergeAlternately(self, word1: str, word2: str) -> str:
 3         n, m, i = len(word1), len(word2), 0
 4         ans = ""
 5         while i < n or i < m:
 6             if i < n:
 7                 ans += word1[i]
 8             if i < m:
 9                 ans += word2[i]
10             i += 1
11         return ans

参考博客https://www.cnblogs.com/liu-myu/p/16817926.html

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值