From 83b8091fa60ac730493dca1ea0465f8ca27a7405 Mon Sep 17 00:00:00 2001 From: floraachy <1622042529@qq.com> Date: Mon, 4 Mar 2024 15:19:13 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=A4=E6=9B=BF=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 交替合并字符串.py | 64 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/交替合并字符串.py b/交替合并字符串.py index a035ed7..3da0160 100644 --- a/交替合并字符串.py +++ b/交替合并字符串.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:]