Notice
Recent Posts
Recent Comments
Link
리미로그
[programmers] 프로그래머스 신고 결과 받기 (lv2, java) 본문
https://school.programmers.co.kr/learn/courses/30/lessons/60057
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문자열의 압축 길이를 1부터 문자열 길이까지 반복하여 진행한다.
처음 해당 길이만큼의 부분 문자열을 prev에 저장하고, 반복문을 돌면서 문자열이 같아서 누적해서 압축할 수 있는지 아닌지를 확인한다.
문제를 처음에 제출했을 때 60퍼센트 정도 맞다고 나왔는데,
그때 틀린 부분이 바로 total 과 temp 길이를 확인하는 if~else if~else 부분이다.
같은 부분이 한 번 밖에 없었다면 1을 출력하지 않고 문자열만 출력해야 한다.
같은 부분이 여러 개라면 숫자를 출력한 후 문자열을 출력해야 한다.
temp는 반복문을 돌면서 저장한 문자열을 담고 있는데 남아있는 게 있다면 같이 출력해줘야 한다.
import java.io.*;
public class Solution {
public static int solution(String c) {
String s = c;
int minLen = s.length(); //압축했을 때 가장 짧은 문자열 길이
StringBuilder temp = new StringBuilder();; //i길이만큼 잠시 저장하는 문자열
String prev = null; //바로 직전 i길이 만큼의 문자열
StringBuilder compress = new StringBuilder(); //압축 완료 문자열
for(int i=1; i<= s.length() ; i++) {
prev = s.substring(0,i);
int cnt = i-1;
int total = 1;
for(int j=i; j < s.length(); j++) {
temp.append(s.charAt(j));
cnt--;
if(cnt < 0) { //같은 길이만큼 끊었을 때
if(temp.toString().equals(prev)){ //이전의 문자열과 같다면
total++;
temp.setLength(0);
cnt = i-1;
}
else { //이전의 문자열과 같지 않다면
if(total != 1) compress.append(total).append(prev);
else compress.append(prev);
total = 1;
prev = temp.toString();
}
temp.setLength(0); //초기화
cnt = i-1;
continue;
}
}
if(total > 1) {
if(temp.length() != 0) compress.append(total).append(prev).append(temp);
else compress.append(total).append(prev);
}
else if(temp.length() != 0) compress.append(prev).append(temp);
else compress.append(prev);
prev = null;
temp.setLength(0);
minLen = Math.min(minLen, compress.length());
compress.setLength(0);
}
return minLen;
}
}
'algorithm > programmers' 카테고리의 다른 글
[programmers] 프로그래머스 신고 결과 받기 (lv1, python) (0) | 2022.07.04 |
---|