python_practice/交替合并字符串.py

94 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
题目:给你两个字符串 word1 和 word2 。请你从 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
"""
class Solution(object):
def mergeAlternately_0(self, word1, word2):
"""
菜鸟写法:写的好像比较复杂,但是胜在实现了。
:type word1: str
:type word2: str
:rtype: str
"""
target = []
if len(word1) >= len(word2):
_word1 = word1[:len(word2)]
_word2 = word2
_word3 = word1[len(word2):]
else:
_word1 = word1
_word2 = word2[:len(word1)]
_word3 = word2[len(word1):]
for i in list(zip(_word1, _word2)):
target.append(i[0])
target.append(i[1])
target.extend(_word3)
return "".join(target)
def mergeAlternately_1(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""
target = ""
if len(word1) >= len(word2):
_word1 = word1[:len(word2)]
_word2 = word2
_word3 = word1[len(word2):]
else:
_word1 = word1
_word2 = word2[:len(word1)]
_word3 = word2[len(word1):]
for i in range(len(_word1)):
target = target + _word1[i] + _word2[i]
return target + _word3
def mergeAlternately_2(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""
word_merge = ""
for i in range(0, min(len(word1), len(word2))):
word_merge = word_merge + word1[i] + word2[i]
if len(word1) > len(word2):
word_merge = word_merge + word1[i + 1:]
else:
word_merge = word_merge + word2[i + 1:]
return word_merge
def mergeAlternately_3(self, word1: str, word2: str) -> str:
lw = min(len(word1), len(word2))
return ''.join(word1[i] + word2[i] for i in range(lw)) + word1[lw:] + word2[lw:]