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

โปรแกรมตรวจสอบการแมป 1-to-1 ระหว่างสตริงสองสตริงใน Python

ให้สตริง s, t ตรวจสอบว่าสร้าง mapping 1-to-1 จากตัวอักษร s ไป t ได้หรือไม่ (ลำดับคงที่)

ตัวอย่าง: s="papa", t="lili" → True (p→l, a→i)

อัลกอริธึม Two Dictionaries

  • s_dict: mapping s→t, t_dict: mapping t→s
  • เดินคู่ตัวอักษร: ถ้า mapping ชน → False, มิฉะนั้นสร้าง mapping ใหม่

การนำไปใช้

class Solution:
    def solve(self, s, t):
        s_dict = {}
        t_dict = {}
        for i in range(min(len(s), len(t))):
            if s[i] in s_dict:
                if s_dict[s[i]] != t[i]:
                    return False
            elif t[i] in t_dict:
                if t_dict[t[i]] != s[i]:
                    return False
            else:
                s_dict[s[i]] = t[i]
                t_dict[t[i]] = s[i]
        return True

ob = Solution()
print(ob.solve("papa", "lili"))  # True