728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/60057
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
반응형
728x90
👩💻 코드
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int CompressStr(const string &str, int length){
string result;
string prev = str.substr(0, length);
int count = 1;
for (size_t i = length; i < str.length(); i += length) {
string current = str.substr(i, length);
if (current == prev) {
count++;
} else {
result += (count > 1 ? to_string(count) : "") + prev;
prev = current;
count = 1;
}
}
result += (count > 1 ? to_string(count) : "") + prev;
return result.length();
}
int solution(string s) {
int minLength = s.length();
for(size_t i=1; i<=s.length()/2; i++){
minLength = min(minLength, CompressStr(s, i));
}
return minLength;
}
📝 풀이
문자열을 문자의 단위 길이만큼 압축하여 길이를 return하는 CompressStr 함수를 구현합니다.
문자열 처음부터 문자의 단위 길이만큼 비교하여 counting을 합니다.
counting한 int 변수를 그대로 string으로 바꾸어 자릿수가 두 자리 이상인 경우도 올바르게 압축됩니다.
최종적인 문자열의 길이를 return 합니다.
문자의 단위 길이를 1부터 문자열의 반까지 반복하여 가장 짧게 압축된 문자열의 길이 갱신합니다.
반복문이 종료되면 최종적으로 가장 짧게 압축된 문자열의 길이를 return 합니다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 후보키 (0) | 2024.10.17 |
---|---|
[프로그래머스] 점 찍기 (0) | 2024.10.14 |
[프로그래머스] 광물 캐기 (0) | 2024.10.11 |
[프로그래머스] 우박수열 정적분 (0) | 2024.10.11 |
[프로그래머스] 멀쩡한 사각형 (1) | 2024.10.10 |