728x90

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/17684

풀이 - 나의 생각

1. List에 알바벳 A ~ Z를 넣는다.


2. LZW 압축 진행


 2-1. 주어진 문자열을 한글자씩 가져온다.
(현재 문자열이 W, 다음 문자열 C)

 

2-2. W+C가 List에 있는지 확인
Y -> W = W+C, C는 원래 C의 다음 문자열, 2-2로
N -> List에 W를 넣고 List에서 W의 위치를 answer에 저장, 2-1로

 

 

1은 그냥 for문으로 알파벳을 넣어줬다.

 

다른 좋은 방법 아시는 분은 댓글 부탁드립니다.

 

W, C는 W+C가 List에 있으면 계속해서 쌓여간다.

 

예를 들어 W+C가 계속해서 List에 없었던 문자라고 가정을 하겠다.

 

No. W C List.contains(W+C)
1 K A true
2 A K true
3 K A true
4 KA O false
5 O   true

 

4번을 보면 그 전에 W+C(KA)가 이미 List에 들어있던 문자이기에

 

W = W+C, C = (이전)C+1 이 된 걸 볼 수 있다.

 

이건 msg.substring(2, 4)와 같다.

 

그래서 start, end라는 int형 변수를 두어서

 

W = msg.substring(start, end);

C = msg.substring(end, end<msg.length()?end+1:end);

 

이렇게 지정을 해주었다.

 

end<msg.length()?end+1:end 를 해주는 이유는

 

StringIndexOutOfBoundsException를 방지해주기 위해서,

 

쉽게 말해 msg의 범위를 넘어가지 않기 위해서이다.

 

 

이후에는 W+C가 List에 들어있을때까지

 

W를 키워간다.(end++)

 

그러다가 List에 W+C가 들어있을면

 

그 위치를 저장하고

 

start를 end 위치로 바꿔주고 다시 반복하면 된다.

 

아 그리고 팁으로

 

List를 배열로 바꾸는 방법!!!

 

int[] answer;

answer = list.stream().mapToInt(Integer::intValue).toArray();

 

실제로 쓰려다 까먹는 경우가 많긴한데

 

기억하면 좋다.

 

코드

 

import java.util.*;
/*
1. List에 알바벳 A ~ Z를 넣는다.
2. LZW 압축 진행
    2-1. 주어진 문자열을 한글자씩 가져온다.
         현재 문자열이 W, 다음 문자열 C
    2-2. W+C가 List에 있는지 확인
        Y -> W = W+C, C는 원래 C의 다음 문자열, 2-2로
        N -> List에 W를 넣고 List에서 W의 위치를 answer에 저장, 2-1로
*/
class Solution {
    public int[] solution(String msg) {
        int[] answer;
        List<String> LZW = new ArrayList<>();
        List<Integer> index = new ArrayList<>();
        for(char c = 'A'; c <= 'Z'; c++){
            LZW.add(String.valueOf(c));
        }
        
        String[] words = msg.split("");
        String W ="", C;
        int start = 0, end = 1;
        while(end <= msg.length()){
            W = msg.substring(start, end);
            C = msg.substring(end, end<msg.length()?end+1:end);
            
            if(!LZW.contains(W+C)){
                index.add(LZW.indexOf(W)+1);
                LZW.add(W+C);
                start = end;
            }
            end++;
        }
        
        if(LZW.contains(W)){
            index.add(LZW.indexOf(W)+1);
        }else{
            index.add(LZW.size());
        }
        
        answer = index.stream().mapToInt(Integer::intValue).toArray();
        return answer;
    }
}

 

 

 

 

 

 

 

다음에 또 봐요

 

+ Recent posts