https://school.programmers.co.kr/tryouts/85896/challenges?language=javascript
문자열을 계속 잘라서 비교하는 함수를 만든 다음에 재귀함수를 통해 남은 문자열이 있으면 계속 돌아가도록 만들었다.
function solution(s) {
const splitString = (str) => {
const arr = [...str];
const x = arr[0];
let matchX = 0;
let notX = 0;
for (let i = 0 ; i < arr.length; i++) {
if (x === arr[i]) {
matchX++;
} else {
notX++;
}
if (matchX === notX) {
return str.slice(i+1);
}
}
}
let result = 0;
while(true){
s = splitString(s);
result++;
if (!s) {
return result;
}
}
}
채점을 해봤더니 150ms까지 나오는게 보여서 리팩토링을 진행했다.
function solution(s) {
let result = 0;
let i = 0;
while (i < s.length) {
let countX = 1;
let countNotX = 0;
const x = s[i];
i++;
while (i < s.length) {
if (s[i] === x) countX++;
else countNotX++;
i++;
if (countX === countNotX) break;
}
result++;
}
return result;
}
결과적으로 최대 52ms까지 속도가 향상된 것을 확인할 수 있었다.