Dùng OrderedDict.fromkeys() để giữ thứ tự xuất hiện đầu tiên của từng ký tự, sau đó kiểm tra pattern.
Ví dụ
from collections import OrderedDict
def check_order(text, pattern):
od = OrderedDict.fromkeys(text) # Loại trùng, giữ thứ tự
idx = 0
for ch in od:
if ch == pattern[idx]:
idx += 1
if idx == len(pattern):
return "Thứ tự pattern đúng"
return "Thứ tự pattern sai"
s = "Hi Mark"
p = "Ma"
print("Chuỗi:", s)
print("Pattern:", p)
print(check_order(s, p))
Kết quả
Chuỗi: Hi Mark Pattern: Ma Thứ tự pattern đúng
Giải thích
OrderedDict.fromkeys(text)tạo dict với key là các ký tự duy nhất theo thứ tự xuất hiện.- Duyệt key của OrderedDict, so khớp với pattern lần lượt.
- Nếu khớp hết pattern -> đúng thứ tự.
- Python 3.7+ dict thường cũng giữ thứ tự chèn, nhưng OrderedDict rõ ý định hơn.