프로그래밍 공방

[프로그래머스] 압축 본문

개발/문제해결

[프로그래머스] 압축

hyosupsong 2020. 11. 25. 00:22

문제

programmers.co.kr/learn/courses/30/lessons/17684

 

코딩테스트 연습 - [3차] 압축

TOBEORNOTTOBEORTOBEORNOT [20, 15, 2, 5, 15, 18, 14, 15, 20, 27, 29, 31, 36, 30, 32, 34]

programmers.co.kr

문제해결방법

문제에 나와 있는 LZW 압축 과정을 그대로 코딩해줘서 풀었습니다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package Programmers;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
class Word {
    int index;
    String word;
    
    Word(int index, String word) {
        this.index = index;
        this.word = word;
    }
}
 
public class Solution_압축 {
 
    public static List<Word>[] words = new ArrayList[50];
    
    public static boolean startWith(String s, String word) {
        boolean check = true;
        if(s.length()<word.length()) check = false;
        else {
            for(int i=0; i<word.length(); i++) {
                if(s.charAt(i)!=word.charAt(i)) {
                    check = false;
                    break;
                }
            }
        }
        return check;
    }
    
    public static int[] solution(String msg) {
        List<Integer> indexList = new ArrayList<>();
        for(int i=0; i<words.length; i++) words[i] = new ArrayList<>();
        for(int i=1; i<=26; i++) words[1].add(new Word(i, (char)('A'+i-1)+""));
        int maxWordLength = 1;
        int nextIndex = 27;
        loop:while(msg.length()>0) {
            for(int i = maxWordLength; i>0; i--) {
                for(int j=0; j<words[i].size(); j++) {
                    if(startWith(msg, words[i].get(j).word)) {
                        String word = words[i].get(j).word;
                        int length = word.length();
                        indexList.add(words[i].get(j).index);
                        msg = msg.substring(length);
                        if(msg.length()!=0) {
                            words[length+1].add(new Word(nextIndex++, word+msg.charAt(0)));
                        }
                        if(maxWordLength<length+1) maxWordLength=length+1;
                        continue loop;
                    }
                }
            }
        }
        int[] answer = new int[indexList.size()];
        for(int i=0; i<answer.length; i++) answer[i] = indexList.get(i);
        return answer;
    }
    
    public static void main(String[] args) {
        String msg = "";
        System.out.println(Arrays.toString(solution(msg)));
    }
}
cs


코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.