변수 cntSame
와 변수 cntDiff
를 사용하여 기준이 되는 글자와 같은 글자가 나오는 횟수와 다른 글자가 나오는 횟수를 헤아린다. 두 개의 변수에 저장된 값이 같아지면 두 변수를 초기화 하며 새롭게 탐색을 이어나갈 수 있게 했다.
function solution(s) {
var answer = 0;
let arr = s.split('');
let cntSame = 0, cntDiff = 0;
let cur;
for(let i=0;i<s.length;i++){
// 첫 글자 설정
if(cntSame === 0) cur = arr[i];
// 글자 수 세기
if(arr[i] === cur) cntSame++;
else cntDiff++;
// 결과 수정 및 초기화
if(cntSame === cntDiff){
answer++;
cntSame = 0;
cntDiff = 0;
}
}
// (문제 조건)두 횟수가 다른 상태에서 더 이상 읽을 글자가 없다면 문자열 분리
if(cntSame !== cntDiff) answer++;
return answer;
}