728x90
오늘의 문제
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:
- Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
- Align the substitution table with the regular English alphabet.
- Each letter in message is then substituted using the table.
- Spaces ' ' are transformed to themselves.
- For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').
Return the decoded message.
제한사항
- 26 <= key.length <= 2000
- key consists of lowercase English letters and ' '.
- key contains every letter in the English alphabet ('a' to 'z') at least once.
- 1 <= message.length <= 2000
- message consists of lowercase English letters and ' '.
입출력 예
key | message | return |
"the quick brown fox jumps over the lazy dog" | "vkbs bs t suepuv" | "this is a secret" |
"eljuxhpwnyrdgtqkviszcfmabo" | "zwx hnfx lqantp mnoeius ycgk vcnjrdb" | "the five boxing wizards jump quickly" |
풀이
class Solution {
public String decodeMessage(String key, String message) {
// key 26자를 알파벳 순서로 치환
StringBuilder sb = new StringBuilder();
key = key.replace(" ", "");
List<Character> alphabet = new ArrayList<>(26);
// key로 알파벳 순서 치환
for(int i=0; i<key.length(); i++) {
char value = key.charAt(i);
if(!alphabet.contains(value)) alphabet.add(value);
}
// message 해독
for(int i=0; i<message.length(); i++) {
char value = message.charAt(i);
if(message.charAt(i) == ' ') sb.append(value);
else sb.append((char) (alphabet.indexOf(value) + 'a'));
}
return sb.toString();
}
}
공백이 있는 경우를 감안해 key의 공백을 모두 제거해주었다. 나오지 않은 알파벳에 대하여 alphabet에 순서를 치환해주고, 해당 인덱스를 통해 message를 해독하였다.
출처: LeetCode, https://leetcode.com/problems/decode-the-message/
728x90
'코딩테스트 연습 > 99클럽' 카테고리의 다른 글
[99클럽] 99클럽 코테 스터디 33일차 TIL - 정렬 (0) | 2024.06.21 |
---|---|
[99클럽] 99클럽 코테 스터디 32일차 TIL - 정렬 (0) | 2024.06.20 |
[99클럽] 99클럽 코테 스터디 30일차 TIL - 문자열 (0) | 2024.06.18 |
[99클럽] 99클럽 코테 스터디 29일차 TIL - 문자열 (0) | 2024.06.17 |
[99클럽] 99클럽 코테 스터디 28일차 TIL - 배열 (Array) (0) | 2024.06.16 |