檢查 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
- 如果 flag 為 True,則:
- 否則:
- index := index + 1
- 如果字串[index] 等於 c,則:
- 返回 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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP