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
相关推荐
小高求学之路9 小时前
计算机视觉、YOLO算法模型训练、无人机监测人员密集自动识别
算法·yolo·计算机视觉
散峰而望9 小时前
【基础算法】剪枝与记忆化搜索:算法优化的双刃剑,效率倍增的实战指南
算法·机器学习·剪枝
m0_748873559 小时前
C++与Rust交互编程
开发语言·c++·算法
ZTLJQ16 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
2401_8914821716 小时前
多平台UI框架C++开发
开发语言·c++·算法
H5css�海秀16 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---17 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
88号技师17 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t1987512817 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神17 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先