[프로그래머스] 압축 (Java)

nnm·2020년 4월 19일
0

프로그래머스 압축

문제풀이

지문을 그대로 구현하면 된다.

  • 26개의 알파벳을 저장하고 있는 사전(HashMap)을 만든다.
  • 사전에 있는지 없는지 확인하며 문자열 압축과 사전 등록을 수행한다.
  • 문자열의 마지막 인덱스에 도달했을 때를 따로 처리해준다.

구현코드

import java.util.*;

class Solution {
	public int[] solution(String msg) {
        ArrayList<Integer> compress = new ArrayList<>();
        HashMap<String, Integer> dic = new HashMap<>();
      
        initDic(dic);
        
        int dicIdx = 27;
        boolean isEnd = false;

        for(int idx = 0 ; idx < msg.length() ; ++idx) {
            String word = msg.charAt(idx) + "";
            
            while(dic.containsKey(word)){
                idx++;
                if(idx == msg.length()) {
                	isEnd = true;
                	break;
                }
                word += msg.charAt(idx);
            }
            
            if(isEnd) {
            	compress.add(dic.get(word));
            	break;
            }
            
            compress.add(dic.get(word.substring(0, word.length() - 1)));
            dic.put(word, dicIdx++);
            
            idx--;
        }
        
        int[] answer = new int[compress.size()];
        for(int i = 0 ; i < answer.length ; ++i){
            answer[i] = compress.get(i);
        }
      
        return answer;
    }
    
    public void initDic(HashMap<String, Integer> dic) {
        char ch = 'A';
        
        for(int i = 1 ; i < 27 ; ++i){
            dic.put(ch + "", i);
            ch += 1;
        }
    }
}
profile
그냥 개발자

0개의 댓글