檢查 Python 中某個字元的所有出現是否相鄰


假設我們有一個字串 s 和另一個字元 c,我們需要檢查 c 的所有出現是否在 s 中相鄰。如果字元 c 不存在於 s 中,則也返回 True。

因此,如果輸入類似於 s = "bbbbaaaaaaaccddd",c = 'a',則輸出為 True。

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

  • flag := False
  • index := 0
  • n := 字串長度
  • 當 index < n 時,執行:
    • 如果字串[index] 等於 c,則:
      • 如果 flag 為 True,則:
        • 返回 False
      • 當 index < n 且字串[index] 等於 c 時,執行:
        • index := index + 1
      • flag := True
    • 否則:
      • index := index + 1
  • 返回 True

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

示例

 線上演示

def solve(string, c) :
   flag = False
   index = 0
   n = len(string)
   while index < n:
      if string[index] == c:
         if (flag == True) :
            return False
         while index < n and string[index] == c:
            index += 1
         flag = True
      else :
         index += 1
   return True
s = "bbbbaaaaaaaccddd"
c = 'a'
print(solve(s, c))

輸入

"bbbbaaaaaaaccddd", "a"

輸出

True

更新於:2020-12-29

277 次檢視

開啟你的職業生涯

完成課程獲得認證

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