ZhongKuo0228 / study

0 stars 0 forks source link

1768. Merge Strings Alternately #59

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

穿插 word1, word2 用 zip 來取相同 index 最後把較長的 append 進來

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        ans = ""
        min_len = min(len(word1), len(word2))
        for w1, w2 in zip(word1, word2):
            ans += w1
            ans += w2
        ans += word1[min_len:]
        ans += word2[min_len:]
        return ans
fockspaces commented 11 months ago

GPT 改進版本:

  1. 用 list append 而不是直接 "+=" 字串,因為 += 相當要創新的記憶體給字串 assign,會更沒效率
  2. zip_longest 可以去取最長的那段,再透過 fillvalue 參數,把較短的那段用 "" placement 掉
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        ans = []
        for w1, w2 in zip_longest(word1, word2, fillvalue = ""):
            ans.append(w1)
            ans.append(w2)
        return "".join(ans)