[Programmers] #181932 - 코드 처리하기 [Java][C++][Python]
[Programmers] #181932 - 코드 처리하기 [Java][C++][Python]
1. 아이디어
문자열 code를 순회하며, 현재 문자가 "1"이면 mode를 전환하고 다음 문자로 넘어간다. "1"이 아니면 mode가 1이면서 인덱스가 홀수일 때, 또는 mode가 0이면서 인덱스가 짝수일 때 ret에 문자를 추가한다. 따라서 mode와 인덱스가 모두 홀수거나 모두 짝수일 때만 문자를 추가하면 된다.
순회를 마쳤을 때 ret이 비어있는지 여부만 체크해서 "EMPTY"를 반환해야 하는지 판단만 주의하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = code의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public String solution(String code) {
StringBuilder ret = new StringBuilder();
int mode = 0;
for (int i = 0; i < code.length(); i++) {
char c = code.charAt(i);
if (c == '1') {
mode = 1 - mode;
continue;
}
if (i % 2 == mode) ret.append(c);
}
if (ret.isEmpty()) return "EMPTY";
return ret.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;
string solution(string code) {
string ret;
int mode = 0;
for (int i = 0; i < code.size(); i++) {
char c = code[i];
if (c == '1') {
mode = 1 - mode;
continue;
}
if (i % 2 == mode) ret += c;
}
if (ret.empty()) return "EMPTY";
return ret;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solution(code):
ret = []
mode = 0
for i, c in enumerate(code):
if c == "1":
mode = 1 - mode
continue
if i % 2 == mode:
ret.append(c)
if ret:
return "".join(ret)
return "EMPTY"
This post is licensed under CC BY 4.0 by the author.