[Programmers] #120892 - 암호 해독 [Java][C++][Python]
암호문에서 code의 배수 위치에 있는 문자만 순서대로 뽑아 원문을 복원하는 문제.
[Programmers] #120892 - 암호 해독 [Java][C++][Python]
1. 아이디어
1부터 세는 위치 기준으로 code의 배수 위치에 있는 문자만 순서대로 모은다. 0-based 인덱스로는 code - 1에서 시작해 code 간격으로 건너뛰면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N / M)$ | $O(N / M)$ |
($N$ = cipher의 길이, $M$ = 입력값 code. 결과 문자열의 길이는 $N / M$이다)
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.