[Programmers] 위장 - 해시

동민·2021년 3월 11일
0
import java.util.HashMap;

// 위장 - 해시
public class Camouflage {
	
	// 예를 들어 상의 2, 하의 1, 모자 1의 경우 입는 경우, 입지 않는 경우의 조합으로 (2+1)*(1+1)*(1+1) 에서 문제 조건에서 최소 한 개의 의상은 입으므로 아무것도 입지 않는 경우를 빼  (2+1)*(1+1)*(1+1)-1 과 같은 원리로 문제를 해결
	public int solution(String[][] clothes) {
		int answer = 1;

		HashMap<String, Integer> map = new HashMap<>(); // Map<착용부위, 중복 개수>

		for (String[] ele : clothes) { // 2차원 배열의 for-each문
			if (map.containsKey(ele[1])) { // map.containsKey : 키를 포함하고 있을 때
				map.replace(ele[1], map.get(ele[1]) + 1); // 착용부위가 중복 일때 map.replace 함수로 1을 증가 시킴
			} else {
				map.put(ele[1], 1);
			}
		}

		for (String ele : map.keySet()) {
			answer *= (map.get(ele) + 1);
		}
		return answer - 1; // 아무것도 입지 않는 경우 -1
	}

	public static void main(String[] args) {

		Camouflage s = new Camouflage();

		String[][] clothes1 = { { "yellow_hat", "headgear" }, { "blue_sunglasses", "eyewear" },
				{ "green_turban", "headgear" } };
		String[][] clothes2 = { { "crow_mask", "face" }, { "blue_sunglasses", "face" }, { "smoky_makeup", "face" } };
		String[][] clothes3 = { { "yellow_hat", "headgear" }, { "blue_sunglasses", "eyewear" },
				{ "green_turban", "headgear" }, { "neck tie", "neck" } };

		System.out.println(s.solution(clothes1)); // 5
		System.out.println(s.solution(clothes2)); // 3
		System.out.println(s.solution(clothes3)); // 11

	}
}
Map.containsKey(Object key) : 키를 포함하고 있는지 구하는 함수
Map.replace(Object key, Object value) : 해당 key의 value를 해당 value로 변경
profile
BE Developer

0개의 댓글