-
[프로그래머스, Lv1] 문자열 자르기알고리즘 문제/Java 2024. 8. 13. 20:54
코딩테스트 연습 - 문자열 나누기 | 프로그래머스 스쿨 (programmers.co.kr)
문제설명
문자열 s가 입력되었을 때 다음 규칙을 따라서 이 문자열을 여러 문자열로 분해하려고 합니다.
- 먼저 첫 글자를 읽습니다. 이 글자를 x라고 합시다.
- 이제 이 문자열을 왼쪽에서 오른쪽으로 읽어나가면서, x와 x가 아닌 다른 글자들이 나온 횟수를 각각 셉니다. 처음으로 두 횟수가 같아지는 순간 멈추고, 지금까지 읽은 문자열을 분리합니다.
- s에서 분리한 문자열을 빼고 남은 부분에 대해서 이 과정을 반복합니다. 남은 부분이 없다면 종료합니다.
- 만약 두 횟수가 다른 상태에서 더 이상 읽을 글자가 없다면, 역시 지금까지 읽은 문자열을 분리하고, 종료합니다.
문자열 s가 매개변수로 주어질 때, 위 과정과 같이 문자열들로 분해하고, 분해한 문자열의 개수를 return 하는 함수 solution을 완성하세요.
제한사항
- 1 ≤ s의 길이 ≤ 10,000
- s는 영어 소문자로만 이루어져 있습니다.
접근 방법
우선 나는 해당 문제를 처음 접했을 때에는 문자열을 분리해야하나 고민이 들었다.
하지만, 문자열을 굳이 자르지 않아도 문제를 풀 수 있을 것 같단 판단이 들어 다음과 같은 순서로 작동하는 코드를 작성했다.
- 첫번째 문자를 저장한다.
- i = 1 ~ string.length을 순회하며, 저장한 문자와 같은지에 대한 여부를 판단한다.
- 같을 경우 targetCount를 + 1 해준다.
- 다를 경우 nonTargetCount를 + 1해준다.
- 만약 targetCount, nonTargetCount가 일치할 경우 answer를 + 1해준다.
해당 과정으로 진행할 경우 target, nonTargetCount가 일치해 answer가 + 1되더라도
target, nonTargetCount를 초기화 하지 않고도 문제 없이 진행이 가능해 코드의 부피를 줄일 수 있었다.
최종 코드
더보기class Solution { public int solution(String s) { int answer = 0, targetCount = 1, nonTargetCount = 0; char target = s.charAt(0); for (int i = 1; i < s.length(); ++i) { if (targetCount == nonTargetCount) { ++answer; target = s.charAt(i); } if(target == s.charAt(i)) { ++targetCount; } else { ++nonTargetCount; } } return answer + 1; } }
'알고리즘 문제 > Java' 카테고리의 다른 글
[프로그래머스, Lv1] 바탕화면 정리 (0) 2024.08.20 [프로그래머스, Lv1] 햄버거 (0) 2024.08.19 [프로그래머스, Lv1] 체육복 (0) 2024.08.12 [프로그래머스, Lv1] 로또의 최고 순위와 최저 순위 (0) 2024.08.06 [프로그래머스, Lv1] 기사단원의 무기 (0) 2024.08.05