c++练习一:交替合并字符串

c++练习一:交替合并字符串

引言

看了一段时间的c++ 拿leetcode上的题目来练练手,话不多说先看题目:

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

实现

有两种方法第一种双重循环暴力破解,第二种利用指针用两个指针 i 和 j,初始时分别指向两个字符串的首个位置。随后的每次循环中,依次进行如下的两步操作:

  • 如果 i 没有超出 word1的范围,则将 word1[i] 加入返回值,并将 i 移动一个位置
  • 如果 j 没有超出 word2的范围,则将 word2[j] 加入返回值,并将 j 移动一个位置

当 i 和 j 都超出对应的范围后,结束循环并返回答案即可。

实现一

#include <iostream>
#include <string>
using namespace std;

class Solution
{
public:
    string mergeAlternately(string word1, string word2)
    {
        string target = "";
        int length1 = word1.size();
        int length2 = word2.size();
        if(length1==length2)
        {
            for(int i=0;i<length1;i++)
            {
                target.append(1,word1[i]);
                target.append(1,word2[i]);
            }
        }else if(length1<length2)
        {
            for(int i=0;i<length1;i++)
            {
                target.append(1,word1[i]);
                target.append(1,word2[i]);
            }

            target.append(word2,length1,length2);
        }
        else
        {
            for(int i=0;i<length2;i++)
            {
                target.append(1,word1[i]);
                target.append(1,word2[i]);
            }

            target.append(word1,length2,length1);
        }
        return target;
    }
};

int main()
{
    Solution s;
    string word1 = "abcd";
    string word2 = "EF";
    string res = s.mergeAlternately(word1, word2);
    cout << res << endl;
}

实现二

#include<iostream>
#include <string>
using namespace std;

class Solution
{
public:
    string mergeAlternately(string word1, string word2)
    {
        int ptr1 = 0, ptr2 = 0;
        string res = "";
        while (ptr1 != word1.size() && ptr2 != word2.size())
        {
            res += word1[ptr1++];
            res += word2[ptr2++];
        }
        if (ptr1 == word1.size() && ptr2 != word2.size())
        {
            while (ptr2 != word2.size())
            {
                res += word2[ptr2++];
            }
        }
        else if (ptr2 == word2.size() && ptr1 != word1.size())
        {
            while (ptr1 != word1.size())
            {
                res += word1[ptr1++];
            }
        }
        return res;
    }
};

int main()
{
    Solution s;
    string word1 = "abcd";
    string word2 = "EF";
    string res = s.mergeAlternately(word1, word2);
    cout << res << endl;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LeonJonson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值