ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 99클럽(2기) - 코테스터디 22일차 TIL # String
    Algorithm 2024. 6. 20. 10:50

    LeetCode - Decode the Message

    You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:

    1. Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
    2. Align the substitution table with the regular English alphabet.
    3. Each letter in message is then substituted using the table.
    4. Spaces ' ' are transformed to themselves.


     

    1. 첫 번째 풀이

     문제를 이해하는 데 5분은 걸린 것 같다. 핵심은 재구성한 key로 치환 테이블을 만드는 과정이다. key에서 최초 등장한 문자열로만 key를 재구성한 후 해당 key와 알파벳을 매핑한 치환 테이블을 만들어 message를 해독한다. 

     

    1) key를 최초 등장한 문자로만 재구성

     first_appearance_letters에 key에서 최초로 등장한 문자만 담는다. 이 때, key에 존재하는 공백은 모두 삭제해야 한다. key를 재구성하는 이유는 message 디코딩을 위한 치환 테이블을 생성하기 위함인데 공백은 치환 테이블에 포함되면 안 되기 때문이다. 

     

    2) 재구성한 key와 알파벳을 매핑시킨 치환 테이블 생성

    파이썬 string 모듈의 ascii_lowercase는 모든 소문자 알파벳 문자열을 제공한다. zip 함수로 1)에서 만든 first_appearance_letters와 alphabet을 매핑한 후 dict 함수로 치환 테이블 딕셔너리를 만들어준다. 

     

    3) 치환 테이블을 통해 message 디코딩

     문제에서 공백은 공백으로 치환한다고 했으므로 messge에 공백이 있으면 공백으로 치환하고, 공백이 없으면 치환테이블에서 해당 문자를 치환한다. 이와 같은 과정으로 디코딩이 끝나면 디코딩된 문자열을 반환한다. 

    import string
    class Solution:
        def decodeMessage(self, key: str, message: str) -> str:
    
            # key에서 최초 등장한 문자만 남긴다
            first_appearance_letters = ""
            for i in key.replace(" ", ""):
                if i not in first_appearance_letters:
                    first_appearance_letters += i
    
            # first_appearance_letters와 abcdef...를 매핑시킨 치환 테이블을 만든다
            alphabet = string.ascii_lowercase
            substitution_table = dict(zip(first_appearance_letters, alphabet))
    
            # message를 치환테이블에 대입해서 디코딩한다
            decoded_message = ""
            for i in message:
                if i == " ":
                    decoded_message += " "
                else:
                    decoded_message += substitution_table[i]
    
            return decoded_message

     

    풀었지만 장황하다...

     

     

    2. 다른 사람의 풀이

     이 풀이에서는 key에 최초 등장한 문자만 남기는 과정이 생략되어있다. 그저 치환 테이블을 만들 때 key의 문자가 치환 테이블의 키로 존재하지 않는지만 확인한다. 이 덕분에 코드가 굉장히 간결해졌다.  

    class Solution(object):
        def decodeMessage(self, key, message):
            dic = {" ": " "}
            letters = "abcdefghijklmnopqrstuvwxyz"
            i = 0
            res = ""
            for k in key:
                if k != " " and k not in dic.keys(): 
                    dic[k] = letters[i]
                    i += 1
            for key in message:
                res += dic[key]
            return res

     

     

    3. 느낀점

     항상 느끼는 거지만 명확한 논리를 가지고 있는 짧은 코드를 만드는 방법을 떠올릴 수 있는 연습을 더 많이 해야할 것 같다. 최초 등장한 문자열만 남겨야 한다는 생각에서 벗어나지 못 해서 더 좋은 풀이를 놓쳤다. 단계별로 접근하면서 '이게 꼭 필요한 과정인가?'라는 질문을 항상 던져봐야겠다.

    댓글

Designed by Tistory.