交替合并字符串

标签: 双指针 字符串

难度: Easy

给你两个字符串 word1word2 。请你从 word1 开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。

返回 合并后的字符串

 

示例 1:

输入:word1 = "abc", word2 = "pqr"
输出:"apbqcr"
解释:字符串合并情况如下所示:
word1:  a   b   c
word2:    p   q   r
合并后:  a p b q c r

示例 2:

输入:word1 = "ab", word2 = "pqrs"
输出:"apbqrs"
解释:注意,word2 比 word1 长,"rs" 需要追加到合并后字符串的末尾。
word1:  a   b 
word2:    p   q   r   s
合并后:  a p b q   r   s

示例 3:

输入:word1 = "abcd", word2 = "pq"
输出:"apbqcd"
解释:注意,word1 比 word2 长,"cd" 需要追加到合并后字符串的末尾。
word1:  a   b   c   d
word2:    p   q 
合并后:  a p b q c   d

 

提示:

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

Submission

运行时间: 16 ms

内存: 16.7 MB

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        w=min(len(word1),len(word2))
        c=word1[:w]
        d=word2[:w]
        e=word1[w:]
        f=word2[w:]
        s=''
        for i in range(w):
            s=c[i]+s
            s=d[i]+s
        return s[::-1]+e+f

Explain

The provided solution intends to merge two strings word1 and word2 by alternating characters from each. It begins by identifying the length of the shorter string (w). It then slices both strings into parts that have equivalent indices (c and d) and the leftover parts (e and f) when one string is longer than the other. In a loop, it alternates adding characters from c and d to a new string s, but it inserts them in reverse order, hence the need to reverse s at the end. After the loop, it appends any leftover characters from the longer string.

时间复杂度: O(n)

空间复杂度: O(n)

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        w = min(len(word1), len(word2)) # Find the length of the shorter word
        c = word1[:w] # Characters from word1 that will be alternated
        d = word2[:w] # Characters from word2 that will be alternated
        e = word1[w:] # Remaining characters of word1 if it is longer
        f = word2[w:] # Remaining characters of word2 if it is longer
        s = '' # Initialize the result string
        for i in range(w): # Alternate characters
            s = c[i] + s # Prepend characters from word1 in reverse
            s = d[i] + s # Prepend characters from word2 in reverse
        return s[::-1] + e + f # Reverse the string and append remaining parts

Explore

这种做法可能是由于编码时的误解或代码错误。在正常情况下,向字符串s的前面添加字符,再在最后进行反转,是不必要且效率较低的,因为每次添加字符到字符串前面都可能涉及到内存中的重新分配和字符复制操作。直接按顺序添加字符到s的后面,不仅更符合直觉,也更高效,因为这样可以避免不必要的字符串反转操作。

如果word1或word2是空字符串,当前的解决方案依然可以正确运行。因为空字符串的长度为0,变量w将被设置为0,循环不会执行,不会添加任何字符到s中。最后,结果字符串s将仅包含非空字符串的剩余部分(如果有的话),这是正确的行为。

是的,有更简单直接的方法来实现这个功能。可以直接使用一个循环来交替从两个字符串中取字符添加到结果字符串的末尾,而不是先添加到前面然后再反转。例如,可以初始化一个空字符串,然后在循环中交替添加来自两个字符串的字符,直到处理完短字符串的所有字符。之后直接将较长字符串的剩余部分追加到结果字符串后面。这样就不需要进行额外的字符串反转操作,代码更为简洁明了。