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
|
import java.util.*;
class Solution {
public int[] solution(String s) {
// 문자열 내부에 존재하는 "},{" 문자열을 split 메서드를 통해 배열로 파싱한다.
// 파싱된 배열은 ["{{2", "2,1", "2,1,3", "2,1,3,4}}"] 형태로 나온다.
String[] split = s.split("\\},\\{");
// 처음 원소의 "{{", 마지막 원소의 "}}"를 제거한다.
split[0] = split[0].replace("{{", "");
split[split.length-1] = split[split.length-1].replace("}}", "");
// 배열의 길이가 튜플의 길이와 같다.
int[] answer = new int[split.length];
// 순서가 보장되는 TreeMap을 활용하여 각 원소의 길이를 key, 원소 문자열을 value로 삽입한다.
// 길이가 짧은 순서부터 튜플이 되기 때문이다.
Map<Integer, String> tm = new TreeMap<>();
for(String str : split) {
tm.put(str.length(), str);
}
// HashSet의 중복 특성을 활용하여 각 원소를 순회하며 튜플 배열을 채운다.
int idx = 0;
Set<String> set = new HashSet<>();
for(int len : tm.keySet()) {
String[] arr = tm.get(len).split(",");
for(String str : arr) {
if(!set.contains(str)) {
set.add(str);
answer[idx] = Integer.parseInt(str);
}
}
idx++;
}
return answer;
}
public static void main(String[] args) {
Solution sol = new Solution();
String s = "{{4,2,3},{3},{2,3,4,1},{2,3}}";
// String s = "{{20,111},{111}}";
// String s = "{{1,2,3},{2,1},{1,2,4,3},{2}}";
// String s = "{{2},{2,1},{2,1,3},{2,1,3,4}}";
// String s = "{{123}}";
sol.solution(s);
}
}
|