C++实现两个字符串交替组合成一个字符串

引言

这道题来自力扣,给出两个字符串,将两个字符串交替着组合成一个字符串。
如:

string str1="abcd";
string str2="hb";
string str = "ahbbcd";
string str1="abcd";
string str2="hbwq";
string str = "ahbbcwdq";
string str1="ab";
string str2="hbwq";
string str = "ahbbwq";

实现

这里会提到两种实现方式。

实现一

第一种是我自己的实现方式:
main.cpp

#include 
#include 
#include 

using namespace std;

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        string strMerge = "";
        if(word1.length() < 1 || word2.length() <1 || word1.length() > 100 || word2.length() > 100)
        {
            return strMerge;
        }
        if(word1.length() == word2.length())
        {
            mergeTwoStringWithSameLength(strMerge,word1,word2,word1.length());
            return strMerge;
        }else if(word1.length() > word2.length())
        {
            mergeTwoStringWithStr1MoreStr2Len(strMerge,word1,word2);
            return strMerge;
        }
        else if(word1.length() < word2.length())
        {
            mergeTwoStringWithStr1LessStr2Len(strMerge,word1,word2);
            return strMerge;
        }
        return strMerge;
    }

    void mergeTwoStringWithSameLength(string &strMerge,string strWorld1,string strWorld2,int nLen)
    {
        for(int i = 0; i < nLen;++i)
        {
            strMerge.push_back(strWorld1[i]);
            strMerge.push_back(strWorld2[i]);
        }
    }

    void mergeTwoStringWithStr1MoreStr2Len(string &strMerge,string strWorld1,string strWorld2)
    {
        string strSub = getExtraString(strWorld1,strWorld2);
        mergeTwoStringWithSameLength(strMerge,strWorld1,strWorld2,strWorld2.length());
        strMerge.append(strSub);
    }

    void mergeTwoStringWithStr1LessStr2Len(string &strMerge,string strWorld1,string strWorld2)
    {
         string strSub = getExtraString(strWorld2,strWorld1);
         mergeTwoStringWithSameLength(strMerge,strWorld1,strWorld2,strWorld1.length());
        strMerge.append(strSub);
    }

    string getExtraString(string strMore,string strLess)
    {
        int nMoreLen = strLess.length();
        string strSub = strMore.substr(nMoreLen);
        return strSub;
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    string str1 = "abcjtr";
    string str2 = "def";
    Solution so;
    string strMerge = so.mergeAlternately(str1,str2);
    QString str = QString::fromStdString(strMerge);
    qDebug()<<"strMerge="<<str;
    qDebug()<<"souce:"<<QString::fromStdString(str1)<<" and"<<QString::fromStdString(str2);

    return a.exec();
}

实现二

第二种实现方式是力扣给出的实现。

class Solution {
public:
string mergeAlternately(string word1, string word2) {
        size_t len1 = word1.size();
        size_t len2 = word2.size();

        string result = "";
        for (int i = 0; i < len1 || i < len2; i++) {
            if (i < len1) result += word1[i];
            if (i < len2) result += word2[i];
        }
        return result;
    }
};

你可能感兴趣的:(Qt,c++,qt,开发语言)