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

วิธีตรวจสอบว่ากลุ่ม 'a' ติดตามด้วยกลุ่ม 'b' ความยาวเท่ากันใน Python

ปัญหา

สตริง s ประกอบด้วย 'a' และ 'b' เท่านั้น ตรวจสอบว่าทุกกลุ่ม 'a' ติดต่อกัน ตามด้วยกลุ่ม 'b' ติดต่อกันที่มีความยาวเท่ากัน

ตัวอย่าง: "abaaabbbaabbaabbab" → กลุ่ม: (ab), (aaabbb), (aabb), (aabb), (ab) → True

แนวทางแก้ปัญหา

  1. นับ 'a' ติดต่อกัน (a_count++)
  2. นับ 'b' ติดต่อกัน (a_count--)
  3. หากหลังจบกลุ่ม a_count != 0 คืน False

ตัวอย่างโค้ด

def solve(s):
    a_count = 0
    string_len = len(s)
    i = 0
    while i < string_len:
        while i < string_len and s[i] == 'a':
            a_count += 1
            i += 1
        while i < string_len and s[i] == 'b':
            a_count -= 1
            i += 1
        if a_count != 0:
            return False
    return True

s = "abaaabbbaabbaabbab"
print(solve(s))  # True

อินพุต / เอาต์พุต

Input: "abaaabbbaabbaabbab"
Output: True