Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมนับ Consistent Strings ใน Python

โจทย์

มีสตริง s (ตัวอักษรไม่ซ้ำ) และอาร์เรย์ words สตริง Consistent = ตัวอักษรทุกตัวอยู่ใน s นับจำนวน Consistent Strings ใน words

ตัวอย่าง: s="px", words=["ad","xp","pppx","xpp","apxpa"] → Consistent: ["xp","pppx","xpp"] → 3

อัลกอริธึม

  1. แปลง s เป็น Set เพื่อ O(1) Lookup
  2. ตรวจสอบแต่ละคำใน words ว่าทุกตัวอักษรอยู่ใน Set หรือไม่

โค้ด Python


def solve(s, words):
    allowed = set(s)
    count = 0
    for word in words:
        if all(c in allowed for c in word):
            count += 1
    return count

s = "px"
words = ["ad","xp","pppx","xpp","apxpa"]
print(solve(s, words))  # Output: 3

Input / Output

Input:  "px", ["ad","xp","pppx","xpp","apxpa"]
Output: 3