檢查給定的字串是否可以透過連線給定的 Python 字串來生成


假設我們有兩個字串 s 和 t 以及 r,我們需要檢查 r 是否等於 s | t 或 r = t + s,其中 | 表示連線。

因此,如果輸入類似於 s = "world" t = "hello" r = "helloworld",則輸出將為 True,因為 "helloworld" (r) = "hello" (t) | "world" (s)。

為了解決這個問題,我們將遵循以下步驟:

  • 如果 r 的大小與 s 和 t 的長度之和不同,則
    • 返回 False
  • 如果 r 以 s 開頭,則
    • 如果 r 以 t 結尾,則
      • 返回 True
  • 如果 r 以 t 開頭,則
    • 如果 r 以 s 結尾,則
      • 返回 True
  • 返回 False

讓我們來看下面的實現來更好地理解:

示例程式碼

線上演示

def solve(s, t, r):
   if len(r) != len(s) + len(t):
      return False

   if r.startswith(s):
      if r.endswith(t):
         return True
         
   if r.startswith(t):
      if r.endswith(s):
         return True
     
   return False  

s = "world"
t = "hello"
r = "helloworld"
print(solve(s, t, r))

輸入

"world", "hello", "helloworld"

輸出

True

更新於:2021年1月16日

瀏覽量:105

開始您的職業生涯

完成課程後獲得認證

開始學習
廣告