문제 요약
[boj] 16472. 고냥이 (node.js)
- 숫자 N과 문자열이 주어진다.
- 주어진 문자열에서 최대 N 종류의 알파벳이 인식 가능할 때,
- 인식 가능한 문자열의 최대 길이를 찾아라
풀이
- 두 포인터 L, R을 조건에 따라 이동하면서 각 char의 등장 횟수를 저장하면
- 이 배열을 통해 조건을 만들어 현재 알파벳의 종류를 알아낼 수 있다.
- L, R 포인터를 조건에 기반해 이동시키며 그 최대 길이를 갱신한다.
내 풀이
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let cnt = 0;
const input = () => stdin[cnt++];
let stdin = [];
rl.on("line", function (line) {
stdin.push(line);
}).on("close", function () {
const N = input();
const str = input();
let arr = [];
let cnt = 0;
let maxLen = -10;
for (let L = 0, R = 0; R < str.length; R++) {
if (!arr[str[R].charCodeAt(0) - 97]) arr[str[R].charCodeAt(0) - 97] = 0;
if (arr[str[R].charCodeAt(0) - 97] == 0) cnt++;
arr[str[R].charCodeAt(0) - 97]++;
if (cnt > N) {
arr[str[L].charCodeAt(0) - 97]--;
if (arr[str[L].charCodeAt(0) - 97] == 0) cnt--;
L++;
}
maxLen = Math.max(maxLen, R - L + 1);
}
console.log(maxLen);
process.exit();
});
- R은 조건에 관계없이 항상 전진한다.
- L~R까지 문자열의 길이는 R-L+1이다.
- charCodeAt(idx) 메서드를 활용하여 L++를 수행한다.