-
[알고리즘] 프로그래머스 문자열 압축 Java(자바)코딩/알고리즘 2022. 1. 4. 16:02
- 문제
https://programmers.co.kr/learn/courses/30/lessons/60057
코딩테스트 연습 - 문자열 압축
데이터 처리 전문가가 되고 싶은 "어피치"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문
programmers.co.kr
- 코드 설명
다른 문제를 풀때 정규식을 사용해서 풀었는데 그것 때문인지 계속 정규식으로 풀려고 고집을 부렸다...
class Solution { static int min_length; static int answer; public int solution(String s) { answer = s.length(); min_length = s.length(); //단위의 수가 1/2를 넘어가면 압축이 안됨 for(int i=0; i<s.length()/2 ; i++){ sol(s, i+1); } return answer; } static void sol(String s, int unit){ int count = 1; String compression = ""; String temp = s.substring(0,unit); int i = 0; for(i=unit; i<=s.length()-unit; i+=unit){ //이전 문자 단위와 같으면 count 증가 if(s.substring(i,i+unit).equals(temp)) count++; else{ if(count > 1) compression = compression.concat(count+temp); else if(count == 1) compression = compression.concat(temp); //문자 단위 교체 temp = s.substring(i,i+unit); count = 1; } } //for문 종료후 마지막 단위 처리 if(count == 1) compression = compression.concat(temp); else compression = compression.concat(count+temp); //남은 문자열 처리 if(i < s.length()) compression = compression.concat(s.substring(i)); answer = Math.min(answer,compression.length()); } }
- 결과
'코딩 > 알고리즘' 카테고리의 다른 글
[알고리즘] 프로그래머스 카카오프렌즈 컬러링북 Java(자바) (0) 2022.01.06 [알고리즘] 프로그래머스 오픈채팅방 Java(자바) (0) 2022.01.05 [알고리즘] 프로그래머스 신규아이디 추천 Java(자바) (0) 2022.01.03 [알고리즘] 프로그래머스 점프와 순간이동 Java(자바) (0) 2022.01.02 [알고리즘] 프로그래머스 디스크 컨트롤러 Java(자바) (1) 2022.01.01