Update 交替合并字符串.py
This commit is contained in:
parent
d88acf6584
commit
83b8091fa6
64
交替合并字符串.py
64
交替合并字符串.py
|
|
@ -27,3 +27,67 @@ 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:]
|
||||
|
|
|
|||
Loading…
Reference in New Issue