알고리즘(Java)/프로그래머스
[프로그래머스, JAVA] 위장
요깨비
2019. 12. 5. 18:07
위 문제는 자바 컬렉션인 Map을 활용하여 해결하였습니다. 옷의 종류를 Key값으로, 각 옷들을 Key값의 List배열에 담아주었습니다.
아래는 코드입니다.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
class Solution {
HashMap<String, ArrayList<String>> clothMap;
int result = 1;
public int solution(String[][] clothes) {
clothMap = new HashMap<>();
ArrayList<String> clothList;
for (int i = 0; i < clothes.length; i++) {
// clothMap.putIfAbsent(clothes[i][0], new ArrayList<String>());
if (clothMap.getOrDefault(clothes[i][1], null) == null) {
System.out.println("!");
ArrayList<String> addList = new ArrayList<String>();
addList.add(clothes[i][0]);
clothMap.put(clothes[i][1], addList);
} else {
ArrayList<String> getClothList = clothMap.get(clothes[i][1]);
getClothList.add(clothes[i][0]);
}
}
Iterator<String> itr= clothMap.keySet().iterator();
while(itr.hasNext()) {
String key = itr.next();
clothList = clothMap.get(key);
result *= (clothList.size()+1);
}
result -= 1;
return result;
}
}
그런데 여기에서 맵 컬렉션에 대해서 이해가 부족했는지 뻘짓거리를 좀 했습니다;; 위에 Iterator를 이용하여 옷들 꺼내는 거 보이시죠?
for (int i = 0; i < clothMap.size(); i++) {
clothList = clothMap.get(clothes[i][1]);
// System.out.println(clothes[i][0] + ": " +clothList.size());
// System.out.println(clothList.toString());
result *= (clothList.size()+1);
}
이런식으로 해서 몇개는 맞고 몇개는 틀렸는데 저기에서 clothes[i][1]가 예시를 들면 옷 3개, 바지 2개일때 cloth[0][1],[1][1],[2][1] 모두
옷을 가리키므로 (3+1) * (3+1) * (3+1) - 1 로 63이라는 말같지도 않은 결과가 나왔습니다. 그냥 Iterator로 키값 순회하면 되는걸...
아직 저는 너무 부족합니다