[Programmers] #181862 - 세 개의 구분자 [Java][C++][Python]
[Programmers] #181862 - 세 개의 구분자 [Java][C++][Python]
1. 아이디어
"a", "b", "c"를 구분자로 문자열을 나누어 문자열 배열로 반환하면 되는 문제다. 빈 배열인 경우만 ["EMPTY"]를 출력하도록 주의만 하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = myStr의 길이)
3. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;
class Solution {
public String[] solution(String myStr) {
StringTokenizer st = new StringTokenizer(myStr, "abc");
if (!st.hasMoreTokens()) return new String[]{"EMPTY"};
String[] arr = new String[st.countTokens()];
for (int i = 0; i < arr.length; i++) {
arr[i] = st.nextToken();
}
return arr;
}
}
StringTokenizer는 한 글자짜리 구분자 여러 개를 한번에 처리할 수 있어 간단하게 해결했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
vector<string> solution(string myStr) {
for (char& c : myStr) {
if (c == 'a' || c == 'b' || c == 'c') c = ' ';
}
stringstream ss(myStr);
vector<string> ans;
string token;
while (ss >> token) ans.push_back(token);
if (ans.empty()) return {"EMPTY"};
return ans;
}
구분자들을 공백으로 치환 후 std::stringstream을 활용해 공백들을 기준으로 토큰들을 받았다.
1
2
3
def solution(myStr):
ans = myStr.translate(str.maketrans("abc", " ")).split()
return ans if ans else ["EMPTY"]
str.maketrans로 구분자들을 공백으로 치환 후 split을 했다.
This post is licensed under CC BY 4.0 by the author.