โจทย์
มีสตริง s (ตัวอักษรไม่ซ้ำ) และอาร์เรย์ words สตริง Consistent = ตัวอักษรทุกตัวอยู่ใน s นับจำนวน Consistent Strings ใน words
ตัวอย่าง: s="px", words=["ad","xp","pppx","xpp","apxpa"] → Consistent: ["xp","pppx","xpp"] → 3
อัลกอริธึม
- แปลง
sเป็น Set เพื่อ O(1) Lookup - ตรวจสอบแต่ละคำใน
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