자바에서는 map함수의 값을 변경할 때 get으로 꺼내온 뒤 put으로 다시 넣어주는 작업이 필요하다.
슬라이딩 윈도우 기법을 활용하여 문제를 해결하였다.
import java.util.*;
class Solution {
public boolean check(Map<String,Integer> map) {
int flag = 0;
Iterator<String> keys = map.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
if(map.get(key) > 0) {
flag = 1;
break;
}
}
if(flag == 0) return true;
return false;
}
public int solution(String[] want, int[] number, String[] discount) {
int start = 0;
int end = start + 10;
int answer = 0;
Map<String,Integer> map = new HashMap<>();
for(int i = 0; i<want.length; i++) {
map.put(want[i], number[i]);
}
//처음
for(int i =0; i < 10; i++) {
if(map.containsKey(discount[i])) map.put(discount[i] , map.get(discount[i])-1);
}
if(check(map)) answer++;
while(end < discount.length) {
if(map.containsKey(discount[start])) map.put(discount[start] ,map.get(discount[start])+1);
if(map.containsKey(discount[end])) map.put(discount[end] ,map.get(discount[end])-1);
start++;
end ++;
if(check(map)) answer++;
}
return answer;
}
}
단순한 문제!