[프로그래머스][3차 압축]-Lv.2

호준·2022년 12월 9일
0

Algorithm

목록 보기
111/111
post-thumbnail

🎉 문제

문제링크

🎉 입/출력 형식

🎉 접근방법

  1. A~Z를 String 형태로 list에 저장한다.
  2. 주어진 msg를 index 0부터 빈 스트링(s)에 붙히면서 list에 있는지 확인한다.
    2-1 list에 존재하면 history에 s를 저장한다.
    2-2 list에 없으면 history의 index 번호는 ans에 저장하고 s는 list에 넣어 준뒤
    s = ""로 초기화하고 index를 -1를 해준다.
  3. index가 msg 길이 만큼 2를 반복한다.
  4. 마지막 history의 index 번호를 ans에 저장하고 반환한다.

🎉 코드

import java.util.*;
class Solution {
    public int[] solution(String msg) {
        int[] answer = {};
        List<Integer> ans = new ArrayList<>();
        List<String> list = new ArrayList<>();
        char temp = 'A';
        // 1. A~Z 넣기
        for(int i=0; i<26; i++){
            String str = String.valueOf((char)(temp+i));
            list.add(str);
        }
        String s = "";
        String history = "";
        for(int i=0; i<msg.length(); i++){
            // 1. list에 포함되는지 확인
            s += msg.charAt(i);
            if(list.contains(s)){
                history = s;
                continue;
            }
            ans.add(list.indexOf(history)+1);
            list.add(s);
            s = "";
            i--;
        }
        ans.add(list.indexOf(history)+1);
        return ans.stream().mapToInt(i->i).toArray();
    }
}
profile
도전하지 않는 사람은 실패도 성공도 없다

0개의 댓글