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

Unique Morse Code Words ใน Python: นับรหัสโมสที่ไม่ซ้ำกัน

แต่ละคำสามารถแปลงเป็นรหัสโมสโดยต่อรหัสของแต่ละตัวอักษร ต้องการนับจำนวนรหัสโมสที่ไม่ซ้ำกันจากรายการคำ

ตารางรหัสโมส (a-z)

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
 "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
 "..-","...-",".--","-..-","-.--","--.."]

ตัวอย่าง

["gin","zen","gig","msg"] → โมส: "--...-.", "--...-.", "--...--.", "--...--." → ไม่ซ้ำ 2 รหัส

ขั้นตอนการแก้ปัญหา

  1. สร้างเซตเก็บรหัสโมสที่ไม่ซ้ำ
  2. วนแต่ละคำ: สร้างรหัสโมสโดยต่อ morse[ord(c)-97]
  3. เพิ่มเข้าเซต
  4. คืนขนาดเซต

การติดตั้งใน Python

class Solution:
    def uniqueMorseRepresentations(self, words):
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
                 "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
                 "..-","...-",".--","-..-","-.--","--.."]
        seen = set()
        for w in words:
            code = ''.join(morse[ord(c)-97] for c in w)
            seen.add(code)
        return len(seen)

ob = Solution()
print(ob.uniqueMorseRepresentations(["gin","zen","gig","msg"]))  # 2

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

Input: ["gin","zen","gig","msg"]
Output: 2