-
프로그래머스 - 문자열 압축 (JavaScript)etc/coding test 2020. 5. 4. 08:30
문제: https://programmers.co.kr/learn/courses/30/lessons/60057
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 해결 과정
1개씩 자르고 길이 확인
2개씩 자르고 길이 확인
3개씩 자르고 길이 확인
...
위의 과정을 최대로 자를 수 있는 길이인 string.length/2 한 후 소수점 이하는 버린 값까지 반복한다.
Ex. 길이가 5인 string이면 최대로 자를 수 있는 길이는 2다.
1. 자를 수 있는 길이를 1부터 max까지 반복하면서
2. 문자열을 압축하고 그 길이가 최소값이면 answer를 교체한다.
2-1) 문자열 압축 과정코드
function solution(s) { var answer = s.length; const max = Math.floor(s.length / 2) + 1; // 자르려는 최대 문자열 단위 let count = 1; // 자르는 단위 길이 max까지 ++ while (count < max) { //문자열 압축하기 let compressedString = ""; for (let i = 0; i < s.length; i += count) { const nowString = s.slice(i, i + count); //비교할 문자열 const check = compressedString.slice( compressedString.length - count, compressedString.length ); if (nowString === check) { const front = compressedString.slice( 0, compressedString.length - count ); let num = 2; let oldCount = ""; // front 끝에서 숫자가 몇자리인지 세야하는디 for (let j = front.length - 1; j >= 0; j--) { if (isNaN(Number(front[j])) === true) { if (oldCount.length > 0) { num = Number(oldCount) + 1; } break; } else { oldCount = front[j] + oldCount; num = Number(oldCount) + 1; // 여기 이걸 안해줘서 개고생을 했다..ㅎㅎ... } } compressedString = front.slice(0, front.length - oldCount.length) + String(num) + check; } else { compressedString += nowString; } } if (compressedString.length < answer) { answer = compressedString.length; } count++; } return answer; }
생각해보고 싶은 점
.
출처:
프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
'etc > coding test' 카테고리의 다른 글
프로그래머스 - 쇠막대기 (JavaScript) (0) 2020.05.05 프로그래머스 - 튜플 (JavaScript) (0) 2020.04.28 프로그래머스 - 124 나라의 숫자 (JavaScript) (0) 2020.04.27 프로그래머스 - 탑 (JavaScript) (0) 2020.04.26 프로그래머스 - 타겟 넘버 (JavaScript) (0) 2020.04.23