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

ตรวจสอบว่าครึ่งหน้าครึ่งหลังของสตริงต่างกันอย่างน้อย 1 ตัวอักษร ใน Python


ปัญหา

ให้สตริงพิมพ์เล็ก ตัดครึ่ง (ถ้าคี่ ตัดกลางทิ้ง) ตรวจสอบว่าครึ่งหน้าและครึ่งหลังมีตัวอักษรต่างกัน (ชนิดหรือความถี่) อย่างน้อย 1 ตัว

ตัวอย่าง

s = "helloohekk" (ยาว 10)
ครึ่งหน้า: "hello" → h:1, e:1, l:2, o:1
ครึ่งหลัง: "ohekk" → o:1, h:1, e:1, k:2
ต่างกัน (มี k ในหลัง, l ในหน้า) → True

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

from collections import Counter

def solve(s):
    n = len(s)
    mid = n // 2
    left = Counter(s[:mid])
    right = Counter(s[mid:])  # ถ้าคี่ ตัวกลางอยู่ใน right
    return left != right

print(solve("helloohekk"))  # True
print(solve("abab"))        # False (a:1,b:1 ทั้งคู่)

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

Input:  "helloohekk"
Output: True