-
22. 문자열 압축코딩 테스트/Level 2 2020. 8. 5. 16:49반응형
https://programmers.co.kr/learn/courses/30/lessons/60057
문자열 압축
2020 KAKAO BLIND RECRUITMENT
4461명 완료코딩테스트 연습 - 문자열 압축
데이터 처리 전문가가 되고 싶은 어피치는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다. 최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데, 문자
programmers.co.kr
파이썬
def solution(s): min_length = [] for length in range(1, len(s) + 1): temp, compressed, count = '', '', 0 for i in range(0, len(s), length): word = s[i: i + length] if word == temp: count += 1 else: compressed += (str(count) if (count > 1) else '') + temp count = 1 temp = word compressed += (str(count) if (count > 1) else '') + temp min_length.append(len(compressed)) return min(min_length)
JS
function solution(s) { const min_length = [] for (let i = 1; i <= s.length; i++) { let temp = '' let compressed = '' let count = 0 for (let j = 0; j < s.length; j += i) { let word = s.slice(j, j + i) if (temp === word) count++ else { compressed += ((count > 1 ? count : '') + temp) count = 1 temp = word } } compressed += ((count > 1 ? count : '') + temp) min_length.push(compressed.length) } return min_length.reduce((a, b) => (a > b) ? b : a) }
Java
class Solution { public int solution(String s) { int answer = 1000; for (var length = 1; length <= s.length(); length++) { var count = 0; var lastStr = ""; var compressedStr = new StringBuilder(); for (var index = 0; index < s.length(); index += length) { var nowStr = s.substring(index, Math.min(index + length, s.length())); if (lastStr.equals(nowStr)) { count++; } else { // 문자열이 바뀜 if (count > 1) compressedStr.append(count); compressedStr.append(lastStr); count = 1; lastStr = nowStr; } } if (count > 1) compressedStr.append(count); compressedStr.append(lastStr); answer = Math.min(compressedStr.length(), answer); } return answer; } }
반응형