[프로그래머스] PS/Java
[lv2] 압축
SH3542
2024. 12. 6. 20:54
https://school.programmers.co.kr/learn/courses/30/lessons/17684
문자열 + 단순 구현
LZW 압축 알고리즘을 구현하는 문제
import java.util.*;
class Solution {
Map<String, Integer> dic = new HashMap<>();
List<Integer> ans = new ArrayList<>();
String msg;
int lastIdx = 27;
void solve() {
StringBuilder ns = new StringBuilder();
int lastNum = -1;
for(int i=0; i<msg.length(); i++) {
ns.append(msg.charAt(i));
if(dic.containsKey(ns.toString())) {
lastNum = dic.get(ns.toString());
}
else {
dic.put(ns.toString(), lastIdx++);
ans.add(lastNum);
i--;
ns.setLength(0);
}
}
ans.add(lastNum);
}
public int[] solution(String msg) {
this.msg = msg;
for(int i=0; i<=25; i++) {
dic.put(String.valueOf((char) ('A'+i)), i+1);
}
solve();
return ans.stream()
.mapToInt(Integer::intValue)
.toArray();
}
}