일부 연속 반복 문자를 포함할 수 있는 문자열을 사용하는 JavaScript 함수를 작성해야 합니다.
함수는 다음과 같이 문자열을 압축해야 합니다 -
'wwwaabbbb' -> 'w3a2b4' 'kkkkj' -> 'k4j'
그리고 압축된 문자열의 길이가 원래 문자열보다 크거나 같으면 원래 문자열을 반환해야 합니다.
예를 들어 -
'aab'는 'a2b1'로 압축될 수 있지만 길이가 4로 늘어나므로 함수는 'aab'를 반환해야 합니다.
예시
이에 대한 코드는 -
const str1 = 'wwwaabbbb';
const str2 = 'kkkkj';
const str3 = 'aab';
const compressString = (str = '') => {
let res = '';
let count = 1;
for(let i = 0; i < str.length; i++){
let cur = str[i];
let next = str[i + 1];
if(cur === next){
count++;
}else{
res += cur + String(count);
count = 1;
};
}
return res.length < str.length ? res : str;
};
console.log(compressString(str1));
console.log(compressString(str2));
console.log(compressString(str3)); 출력
콘솔의 출력은 -
3a2b4 k4j1 aab