문제 URL
https://school.programmers.co.kr/learn/courses/30/lessons/64065
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이 Key Point
- 튜플이 원소 집합은 {a1}, {a1, a2}, {a1, a2, a3}, ... {a1, a2, ...., an}으로 n까지 하나씩 원소를 증가시키면서 집합을 만든다.
즉, an이 포함되는 집합까지 만들면 튜플의 가장 앞의 숫자인 a1은 n번 등장하게 되는 것이다.
문제풀이 Java
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
|
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
class Solution {
public int[] solution(String s) {
int[] answer = {};
s = s.replaceAll("[\\{,\\}]", "/");
String[] tuples = s.split("[//]+");
Map<String, Integer> tuplesCount = new HashMap<>();
for(int j = 0; j < tuples.length; j++){
if (!tuples[j].isEmpty()){
if (tuplesCount.containsKey(tuples[j])){
tuplesCount.replace(tuples[j], tuplesCount.get(tuples[j]) + 1);
}else{
tuplesCount.put(tuples[j], 1);
}
}
}
List<Map.Entry<String, Integer>> sortedTuplesCount = new ArrayList<>(tuplesCount.entrySet());
Collections.sort(sortedTuplesCount, (o1, o2) -> {return o2.getValue().compareTo(o1.getValue());});
answer = new int[sortedTuplesCount.size()];
for(int i = 0; i < answer.length; i++){
answer[i] = Integer.parseInt(sortedTuplesCount.get(i).getKey());
}
return answer;
}
}
|
cs |
Map의 value를 기준으로 오름차순 정렬
1
2
|
List<Map.Entry<String, Integer>> sortedTuplesCount = new ArrayList<>(tuplesCount.entrySet());
Collections.sort(sortedTuplesCount, (o1, o2) -> {return o2.getValue().compareTo(o1.getValue());});
|
cs |
'알고리즘 문제풀이' 카테고리의 다른 글
[프로그래머스 87390] Level2 n^2배열 자르기 (0) | 2022.09.12 |
---|---|
[프로그래머스 12924] 숫자의 표현 (0) | 2022.09.12 |
[프로그래머스 12909] Level2 올바른 괄호 (0) | 2022.09.11 |
[프로그래머스 12941] Level2 최솟값 만들기 (0) | 2022.09.09 |
[프로그래머스 70129] Level2 이진 변환 반복하기 (0) | 2022.09.09 |