본문 바로가기

알고리즘/프로그래머스

[프로그래머스] 보석 쇼핑 / JAVA

문제링크 : https://programmers.co.kr/learn/courses/30/lessons/67258

 

코딩테스트 연습 - 보석 쇼핑

["DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"] [3, 7]

programmers.co.kr

import java.util.*;
class Solution {
    public static int[] solution(String[] gems) {
        int[] answer = new int[2];
        HashSet<String> hs = new HashSet<String>();
        for(int i=0;i<gems.length;i++){
            hs.add(gems[i]);
        }
        int cnt = hs.size();
        int left = 0;
        int right = 0;
        HashMap<String,Integer> hm = new HashMap<String,Integer>();
        int len = 987654321;
        while(right < gems.length){
            while(hm.size() < cnt && right < gems.length){
                String newBosuc = gems[right++];
                if(hm.containsKey(newBosuc)){
                    int count = hm.get(newBosuc);
                    hm.put(newBosuc,count+1);
                }else{
                    hm.put(newBosuc,1);
                }
            }
            while(hm.size() == cnt){
                int newLen = right-left;
                if(len > newLen){
                    len = newLen;
                    answer[0] = left+1;
                    answer[1] = right;
                }
                String erased = gems[left++];
                int count = hm.get(erased);
                if(count==1){
                    hm.remove(erased);
                }else {
                    hm.put(erased,count-1);
                }
            }

        }
        return answer;
    }
}