Post

[Programmers] #120892 - 암호 해독 [Java][C++][Python]

[Programmers] #120892 - 암호 해독 [Java][C++][Python]

문제 링크


1. 아이디어

해독된 암호 문자열은 cipher에서 code의 배수 번째 글자만 모은 문자열이다. code가 첫 문자를 1번으로 판정하므로 code - 1부터 code만큼 더한 것에 해당하는 인덱스의 문자만 모으면 된다.


2. 복잡도

접근시간공간
풀이$O(N / M)$$O(N / M)$

($N$ = cipher의 길이, $M$ = 입력값 code)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
class Solution {
    public String solution(String cipher, int code) {
        StringBuilder sb = new StringBuilder();
        for (int i = code - 1; i < cipher.length(); i += code) {
            sb.append(cipher.charAt(i));
        }

        return sb.toString();
    }
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

string solution(string cipher, int code) {
    string s;
    for (int i = code - 1; i < cipher.size(); i += code) {
        s += cipher[i];
    }

    return s;
}
1
2
def solution(cipher, code):
    return cipher[code - 1 :: code]

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