鱼C论坛

 找回密码
 立即注册
查看: 964|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】1768. Merge Strings Alternately #Easy #Python #C++

[复制链接]
发表于 2023-6-1 09:17:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1:  a   b   c
word2:    p   q   r
merged: a p b q c r

Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1:  a   b
word2:    p   q   r   s
merged: a p b q   r   s

Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1:  a   b   c   d
word2:    p   q
merged: a p b q c   d

Constraints:
1 <= word1.length, word2.length <= 100
word1 and word2 consist of lowercase English letters.

Judy
Python
class Solution(object):
    def mergeAlternately(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: str
        """
        l1 = len(word1)
        l2 = len(word2)
        i1 = 0
        i2 = 0
        r = ""
        while i1 < l1 and i2 < l2:
            r += word1[i1] + word2[i2]
            i1 += 1
            i2 += 1
        r += word1[i1:] + word2[i2:]
        return r

Gray
C++
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int acc = 0;
        string ans;
        for(int i = 0; i < word1.size(); i++){
            ans += word1[i];
            if(acc == word2.size()){//走完
                continue;
            }else {//没走完
                ans+= word2[acc];
            }
            acc++;
        }
        if(acc < word2.size()){
            ans += word2.substr(acc,word2.size()-acc);
        }
        return ans;
    }
};

Mike
C++
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int index = 0;
        string s = "";
        int len1 = word1.length();
        int len2 = word2.length();
        int baselen = min(len1, len2);
        for (int index = 0; index < baselen; index++) {
            s += word1[index];
            s += word2[index];
        }
        if (word2.length() > word1.length()) {
            s += word2.substr(baselen, word2.length() - baselen);
        } else {
            s += word1.substr(baselen, word1.length() - baselen);
        }
        return s;
    }
};

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-28 01:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表