Python程式:檢查一個字串是否可以透過移除一個元素轉換為另一個字串


假設我們有兩個字串s和t,我們要檢查是否可以透過從s中移除一個字母來得到t。

例如,如果輸入是s = "world",t = "wrld",則輸出為True。

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

  • i:= 0
  • n:= s的長度
  • 當 i < n 時,執行以下操作:
    • temp:= s[0:i-1] 與 s[i+1:] 的連線
    • 如果temp等於t,則
      • 返回True
    • i := i + 1
  • 返回False

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

示例

線上演示

class Solution:
   def solve(self, s, t):
      i=0
      n=len(s)
      while(i<n):
         temp=s[:i] + s[i+1:]
         if temp == t:
            return True
         i+=1
      return False
ob = Solution()
s = "world"
t = "wrld"
print(ob.solve(s, t))

輸入

"world", "wrld"

輸出

True

更新於:2020年10月7日

瀏覽量:132

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.