力扣1768

我的答案:

复制代码
class Solution {
public:
    string result;
    int i=0,j=0;
    string mergeAlternately(string word1, string word2) {
    if(word1.length()<1||word2.length()>100){
        return 0;
    }
    if(word1.size()<word2.size()){
        while(i<word1.size()){
            result+=word1[i++];
            result+=word2[j++];
        }
        while(i<word2.size()){
            result+=word2[i++];
        }
        return result;
    }else{
        while(i<word2.size()){
            result+=word1[i++];
            result+=word2[j++];
        }
        while(j<word1.size()){
            result+=word1[j++];
        }
        return result;
    }
    }
};
复制代码
官方解答:
复制代码
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int m = word1.size(), n = word2.size();
        int i = 0, j = 0;
        string ans;
        ans.reserve(m + n);
        while (i < m || j < n) {
            if (i < m) {
                ans.push_back(word1[i]);
                ++i;
            }
            if (j < n) {
                ans.push_back(word2[j]);
                ++j;
            }
        }
        return ans;
    }
};
复制代码

更优解:

复制代码
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        string res;
        int i = 0, j = 0;
        while (i < word1.size() || j < word2.size()) {
            if (i < word1.size()) res += word1[i++];
            if (j < word2.size()) res += word2[j++];
        }
        return res;
    }
};
复制代码

 

posted @   joyfulest  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示