用 Python 檢查字串是否互為旋轉串


假設我們有兩個字串 s 和 t,我們需要檢查 t 是否是 s 的一個旋轉串。

所以,如果輸入為 s = "hello", t = "llohe", 那麼輸出將為 True。

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

  • 如果 s 的長度不等於 t 的長度,則
    • 返回 False
  • temp := 將 s 再連線到 s
  • 如果 temp 中包含 t 的數量 > 0,則
    • 返回 True
  • 返回 False

讓我們看看以下實現來獲得更好的理解:

示例程式碼

即時演示

def solve(s, t):
   if len(s) != len(t):
      return False
 
   temp = s + s
 
   if temp.count(t)> 0:
      return True
   return False

s = "hello"
t = "llohe"
print(solve(s, t))

輸入

"hello", "llohe"

輸出

True

更新日期: 2021-01-15

565 瀏覽量

開啟您職業生涯的火花

完成課程獲得認證

立即開始
廣告
© . All rights reserved.