카카오 코딩테스트 - 압축

greenTea·2023년 3월 12일
import java.util.*;

class Solution {
    public int[] solution(String msg) {
        List<String> list = new ArrayList<>();
        
        char c = 'A';
        for (int i = 0; i < 26; i++) {
            list.add( (char) ('A' + i) +"");
            c++;
        } 
        //단어 등록 과정
       
        List<Integer> ans = new ArrayList<>();
        
        int index =1;  //검사 위치
        
        String word = msg.charAt(0)+""; //현재 단어
        
        while (index <= msg.length()) {
            
            if (index == msg.length()) {
                ans.add(list.indexOf(word)+1);
                break;
            } //끝에 가면 정답 등록 하고 끝내기
            
            char ca = msg.charAt(index); //다음 단어
            
            String wordTotal = word + ca; //현재단어 + 다음 단어
            
            if (list.contains(wordTotal)) { 
                word = wordTotal;
                index++;
                continue;
                //합친 단어를 포함하고 있다면 continue;
            }
            
            list.add(wordTotal);
            ans.add(list.indexOf(word)+1);
            
            word = ""+ca; //다음 단어로 초기화
            index++;
        }
        
        int[] answer = new int[ans.size()];
        for (int i=0;i<ans.size();i++) {
            answer[i] = ans.get(i);
        }
        return answer;
        
    }
                     
}
                     

프로그래머스 알고리즘 : 프로그래머스 압축
참고 블로그 정보가 지식이 되는 과정 - 이철진

profile
greenTea입니다.

0개의 댓글