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
相关推荐
有意义12 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub13 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户7268761033713 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect13 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
明月_清风16 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风16 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研
lizhongxuan1 天前
AI小镇 - 涌现
算法·架构