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

นับจำนวนไดโนเสาร์ในสตริง Python

ภาพรวม

โจทย์นับจำนวนตัวอักษรในสตริง animals ที่เป็น "ไดโนเสาร์" โดยไดโนเสาร์ถูกกำหนดโดยตัวอักษรที่ไม่ซ้ำในสตริง dinosaurs

ตัวอย่าง

animals = "xyxzxyZ"

dinosaurs = "yZ"

ไดโนเสาร์คือ 'y' และ 'Z' (case-sensitive)

ใน animals: 'y' ปรากฏ 2 ครั้ง, 'Z' ปรากฏ 1 ครั้ง → รวม 3

โค้ด Python

class Solution:
    def solve(self, animals, dinosaurs):
        res = 0
        dinosaurs = set(dinosaurs)  # ลบตัวซ้ำ
        for c in dinosaurs:
            res += animals.count(c)
        return res

ob = Solution()
animals = "xyxzxyZ"
dinosaurs = "yZ"
print(ob.solve(animals, dinosaurs))

วิธีอื่น (Pythonic)

def count_dinos(animals, dinosaurs):
    dino_set = set(dinosaurs)
    return sum(1 for c in animals if c in dino_set)

ความซับซ้อน

  • เวลา: O(|animals| + |dinosaurs|) โดยใช้ Set
  • พื้นที่: O(|dinosaurs|) สำหรับ Set

ผลลัพธ์

3