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
相关推荐
不懒不懒15 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr
机器学习之心15 小时前
基于随机森林模型的轴承剩余寿命预测MATLAB实现!
算法·随机森林·matlab
一只小小的芙厨15 小时前
寒假集训笔记·树上背包
c++·笔记·算法·动态规划
马猴烧酒.15 小时前
【面试八股|Java集合】Java集合常考面试题详解
java·开发语言·python·面试·八股
庄周迷蝴蝶15 小时前
四、CUDA排序算法实现
算法·排序算法
以卿a15 小时前
C++(继承)
开发语言·c++·算法
I_LPL15 小时前
day22 代码随想录算法训练营 回溯专题1
算法·回溯算法·求职面试·组合问题
金融RPA机器人丨实在智能15 小时前
2026动态规划新风向:实在智能Agent如何以自适应逻辑重构企业效率?
算法·ai·重构·动态规划
天空属于哈夫克315 小时前
Java 版:利用外部群 API 实现自动“技术开课”倒计时提醒
数据库·python·mysql
喵手16 小时前
Python爬虫实战:全站 Sitemap 自动发现 - 解析 sitemap.xml → 自动生成抓取队列的工业级实现!
爬虫·python·爬虫实战·零基础python爬虫教学·sitemap·解析sitemap.xml·自动生成抓取队列实现