문제
https://www.acmicpc.net/problem/16472
풀이(15분)
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val N = br.readLine().toInt()
val string = br.readLine()
val alphabet = IntArray(26)
var count = 0
var answer = 0
var start = 0
for (end in string.indices) {
if (alphabet[string[end] - 'a']++ == 0) {
count++
}
while (count > N && start < end) {
if (--alphabet[string[start++] - 'a'] == 0) count--
}
answer = maxOf(answer, end - start + 1)
}
println(answer)
}
문제 풀이 전략
- 초기화
- 알파벳 등장 횟수를 기록할 배열 생성 (alphabet[26] = 0)
- 서로 다른 문자를 세는 변수 count = 0
- 최대 길이를 저장할 변수 answer = 0
- 구간 포인터 start = 0, end = 0
- 슬라이딩 윈도우 반복
- end를 문자열 끝까지 이동하며 반복
- string[end] 문자가 처음 등장하면 (alphabet[string[end]-'a'] == 0) → count++
- 알파벳 배열에서 string[end] 값 증가
- 조건 확인 및 구간 조정
- count > N이면, 조건을 만족할 때까지 start를 오른쪽으로 이동
- alphabet[string[start]-'a']--
- 만약 0이 되면 → count--
- start++
- count > N이면, 조건을 만족할 때까지 start를 오른쪽으로 이동
- 최대 길이 갱신
- 매 반복마다 answer = max(answer, end - start + 1)
- 결과 출력
- 반복이 끝나면 answer 출력
'문제 풀이 > 백준' 카테고리의 다른 글
| [백준] Ezreal 여눈부터 가네 ㅈㅈ(Kotlin) (0) | 2025.10.28 |
|---|---|
| [백준] 17352번. 여러분의 다리가 되어드리겠습니다!(Kotlin) (0) | 2025.10.28 |
| [백준] 15553번. 난로(Kotlin) (0) | 2025.10.27 |
| [백준] 16924번. 십자가 찾기(Kotlin) (0) | 2025.10.22 |
| [백준] 24392번. 영재의 징검다리(Kotlin) (0) | 2025.10.21 |