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
相关推荐
matlabgoodboy6 分钟前
Python代做java代码编写C++大数据R语言Hadoop/spark/flink/C语言
java·大数据·python
清水白石0087 分钟前
《Python 编程全景解析:透视性能瓶颈——从基础测速到线上热点诊断的高阶实战》
开发语言·python
清水白石0087 分钟前
Python 服务优雅停机实战:信号处理、资源收尾与 Kubernetes 滚动发布避坑指南
python·kubernetes·信号处理
gc_22998 分钟前
学习python使用Ultralytics的YOLO26进行目标检测的基本用法
python·目标检测·yolo26
2301_804215419 分钟前
模板元编程应用场景
开发语言·c++·算法
2301_8166512212 分钟前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
实心儿儿13 分钟前
C++ —— 红黑树
java·开发语言·算法
炘爚15 分钟前
C++(普通指针和成员的区别、指针的使用场景和存储内容)
数据结构·c++·算法
第一程序员17 分钟前
如何在GitHub上找到适合初学者的Python项目
python·github