[LeetCode] Decode the Message

아르당·2026년 8월 29일

LeetCode

목록 보기
494/565
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 key와 message가 주어지고, 암호 키와 비밀 메시지를 나타낸다. message를 해독하는 단계는 다음과 같다.

  1. key에 나타나는 26개 영어 소문자의 첫 등장 순서를 치환표의 순서로 사용해라.
  2. 대체 표를 일반 영어 알파벳과 함께 정렬해라.
  3. 메시지의 각 문자가 해당 표를 사용하여 치환된다.
  4. 공백 ' '은 그대로 유지된다.
  • 예를 들어, key = "happy boy"가 주어지고(실제 키는 알파벳의 각 글자가 적어도 한 번씩은 포함된다), 부분 치환표로 ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f')를 가진다.

해독된 메시지를 반환해라.

#1

Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: 위 다이어그램은 치환표를 보여준다.
"the quick brown fox jumps over the lazy dog"에서 처음 나타난 글자들로 얻을 수 있다.

#2

Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
Output: "the five boxing wizards jump quickly"

Constraints

  • 26 <= key.length <= 2000
  • key는 영어 소문자와 ' '로 구성된다.
  • key는 영어 알파벳에서 모든 글자('a'에서 'z')를 적어도 하나씩 포함한다.
  • 1 <= message.length <= 2000
  • message는 영어 소문자와 ' '로 구성된다.

Solved

class Solution {
    public String decodeMessage(String key, String message) {
        int a = 97;
        Map<Character, Character> dictionary = new HashMap<>(key.length());

        for(int i = 0; i < key.length(); i++){
            char k = key.charAt(i);

            if(k != ' '){
                if(!dictionary.containsKey(k)){
                    dictionary.put(k, (char) a++);
                }
            }
        }

        StringBuilder sb = new StringBuilder(message.length());

        for(int i = 0; i < message.length(); i++){
            char decoded = ' ';

            if(message.charAt(i) != ' '){
                decoded = dictionary.get(message.charAt(i));
                sb.append(decoded);
            }else{
                sb.append(decoded);
            }
        }

        return sb.toString();
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글