본문 바로가기

프로그래머스

[프로그래머스] 위장 (JAVA)

문제

https://programmers.co.kr/learn/courses/30/lessons/42578

 

코딩테스트 연습 - 위장

 

programmers.co.kr

 

정답

import java.util.HashMap;
import java.util.Iterator;
class Solution {
    public int solution(String[][] clothes) {
   		
        //String[][] clothes = [["yellowhat", "headgear"], ["bluesunglasses", "eyewear"],
                              ["green_turban", "headgear"]]
        
        HashMap<String, Integer> map = new HashMap<>();
		for(String[] clothe : clothes) { //clothe = ["yellowhat", "headgear"]
			String type = clothe[1]; //type = "headgear"
			map.put(type, map.getOrDefault(type, 0) + 1);
		}
		
		Iterator<Integer> it = map.values().iterator();
		int answer = 1;
		
		while(it.hasNext()){
			answer *= it.next().intValue() + 1;
		}
        
		return answer -1;
    }
}

 

※ Iterator

-> 컬렉션에 저장되어 있는 요소들을 읽어오는 인터페이스

public interface Iterator {
    boolean hasNext();
    Object next();
    void remove();
}

boolean hasNext()

 -> 읽어 올 요소가 남아있는지 확인하는 메소드, true/false 반환

 

Object next()

 -> 읽어 올 요소가 남아있는지 확인하는 메소드, true/false 반환

 

void remove()

 -> next()로 읽어 온 요소를 삭제, next() 를 호출한 다음에 remove() 를 호출해야 함