1768. 交替合并字符串(双指针)

246 阅读1分钟

image.jpeg

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第29天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

    image.png

  • 题目示例

    20221023-212255.png

  • 题目提示

    • 1 <= word1.length, word2.length <= 100
    • word1 和 word2 由小写英文字母组成

二、思路分析:

我们今天拿到本题是 leetcode 难度为简单题 1768. 交替合并字符串。题目要求对两个字符串进行交替组合,输出新的字符串。根据示列描述,需要注意几点信息:

  • 两个字符串都是由小写字母组成
  • 两个字符串长度不一样时,较长的字符串剩余的字符需要补充在交替字符串后面

根据题目要求,我们可以使用双指针解答本题,思路如下:

  • 方法一:双指针

    • word1和word2字符交替排序,word1字符排在奇数位,word2字符排在偶数位
    • 可以定义两个指针i,j,分别指向word1和word2
    • while循环,当i指针超过word1时,则继续将word2字符添加到ans中
    • 当j超过word2时,则继续将word1字符添加到ans中
    class Solution(object):
        def mergeAlternately(self, word1, word2):
            """
            :type word1: str
            :type word2: str
            :rtype: str
            """
            n1 = len(word1)
            n2 = len(word2)
    
            i,j = 0,0
            ans = []
    
            while i < n1 or j < n2:
                if i < n1:
                    ans.append(word1[i])
                    i +=1
                if j < n2:
                    ans.append(word2[j])
                    j +=1
            return "".join(ans)
    
  • 方法二:zip_longest()

    • 在python3中,zip_longest()方法可以将较短的字符串自动补齐
    • 使用for循环,遍历zip_longest()将word1和word2组成的序列对
    • 当word1字符为空时,则继续添加word2添加到ans
    • 当word2字符为空时,则继续添加word1添加到ans
    class Solution:
        def mergeAlternately(self, word1: str, word2: str) -> str:
            ans = []
            for a,b in zip_longest(word1, word2, fillvalue=''):
                if a :ans.append(a)
                if b :ans.append(b)
            return "".join(ans)
    

三、总结:

本题是一道关于双指针应用的问题,只需要遍历最长的字符串长度,在遍历过程中对指针的范围进行判断,当超过字符串长度时,则继续添加另外一个字符,AC提交记录:

image.png

  • 时间复杂度:O(n+m),n为word1长度,m为word2长度
  • 空间复杂度:O(n+m),n为word1长度,m为word2长度

以上是本期内容,欢迎大佬们点赞评论,下期见~~~