https://school.programmers.co.kr/learn/courses/30/lessons/140108
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
접근방법
1. 문자열을 순회하며 첫 번째 문자를 기준으로 같은 문자의 개수를 initCount에, 다른 문자의 개수를 targetCount에 기록한다.
2. initCount와 targetCount가 같아질 때마다 부분 문자열을 완성하고 배열 arr에 저장한다.
3.순 회를 마친 후에도 남아 있는 문자가 있다면 나머지 문자열을 하나의 부분 문자열로 간주하여 개수를 추가한다.
제출
function solution(s) {
var answer = 0;
let arr = [];
let initCount = 0;
let targetCount = 0;
let initString = '';
let firstIndex = 0;
for(let i = 0 ; i < s.length ; i ++){
if(initCount == 0){
initString = s[i]
firstIndex = i;
}
if(initString == s[i]){
initCount ++
}else{
targetCount ++
}
if(initCount == targetCount){
initCount = 0
targetCount = 0
arr.push(s.substring(firstIndex, i+1))
}
}
answer = arr.length;
if (initCount !== 0 || targetCount !== 0) {
answer++;
}
return answer;
}
결과 : 100점
'프로그래머스' 카테고리의 다른 글
[프로그래머스] 기사단원의 무기 (0) | 2024.12.11 |
---|---|
[프로그래머스] 명예의 전당(1) (0) | 2024.12.10 |
[프로그래머스] 가장 가까운 같은 글자 (0) | 2024.12.08 |
[프로그래머스] 크기가 작은 부분 문자열 (0) | 2024.12.07 |
[프로그래머스] 둘만의 암호 (0) | 2024.12.06 |