Leetcode 1768. Merge Strings Alternately

Problem

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...

Algorithm

Insert numbers alternately

Code

python3 复制代码
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        ans = ""
        L1, L2, P1, P2 = len(word1), len(word2), 0, 0
        while P1 < L1 or P2 < L2:
            if P1 < L1:
                ans += word1[P1]
                P1 += 1
            if P2 < L2:
                ans += word2[P2]
                P2 += 1
        return ans
相关推荐
小王子10249 分钟前
设计模式Python版 组合模式
python·设计模式·组合模式
利刃大大28 分钟前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
Rachela_z1 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@1 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法
追求源于热爱!1 小时前
记5(一元逻辑回归+线性分类器+多元逻辑回归
算法·机器学习·逻辑回归
ElseWhereR1 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法
Mason Lin1 小时前
2025年1月22日(网络编程 udp)
网络·python·udp
Smark.2 小时前
Gurobi基础语法之 addConstr, addConstrs, addQConstr, addMQConstr
算法
清弦墨客2 小时前
【蓝桥杯】43697.机器人塔
python·蓝桥杯·程序算法
S-X-S2 小时前
算法总结-数组/字符串
java·数据结构·算法