Home 2149번(암호 해독2)
Post
Cancel

2149번(암호 해독2)

첫 시도

  • 문제를 잘못읽어 평문을 암호문으로 만드는 문제로 이해
  • HashMap을 사용해서 키의 문자 1개, 문자열 1줄을 묶어 정렬
  • 그 후 배열에 그대로 넣고 암호화된 문자열을 출력
  • 평문을 만들어야 하므로 실패

해결

  • HashMap을 사용하지 않아도 해결 가능
    1. 키를 배열에 담고 정렬
    2. 입력받은 순서대로 키와 문자열 매칭
    3. 배열 한줄씩 Queue에 삽입
    4. 키값을 확인하면서 원하는 문자열을 결과 배열에 삽입 -> Queue가 빌 때까지 반복
    5. 결과 배열의 1열만 제외하고 2열부터 순서대로 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map.Entry;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String keyword = br.readLine();
        String[] encodedText = br.readLine().split("");
        int N = keyword.length();
        int M = encodedText.length/keyword.length() + 1;

        String[] sortedKW = keyword.split("");
        Arrays.sort(sortedKW);

        String[][] textArr = new String[N][M];
        for(int i = 0; i < N; i++) {
            textArr[i][0] = sortedKW[i];
        }

        int idx = 0;
        for(int i = 0; i < N; i++) {
            for(int j = 1; j < M; j++) {
                textArr[i][j] = encodedText[idx++];
            }
        }

        Queue<String[]> q = new LinkedList<>();
        for(int i = 0; i < N; i++){
            q.add(textArr[i]);
        }

        String[] kwArr = keyword.split("");
        idx = 0;
        while(!q.isEmpty()){
            if(kwArr[idx].equals(q.peek()[0])){
                textArr[idx] = q.poll();
                idx++;
            }
            else {
                q.add(q.poll());
            }
        }
        String result = "";
        for(int i = 1; i < M; i++) {
            for(int j = 0; j < N; j++) {
                result += textArr[j][i];
            }
        }
        System.out.println(result);
    }
}

참고

This post is licensed under CC BY 4.0 by the author.