728x90
문제
https://www.acmicpc.net/problem/2941
첫 번째 풀이
처음 시도한 풀이는 문자열을 인덱스별로 탐색을 진행할때 크로아티아 알파벳의 첫 글자가 나오면 그 다음 문자들을 확인하는 방식을 선택했다. 주의할 점은 for문을 이용한 탐색을 진행할 때 전체 길이의 - 2 까지 탐색한다는 것이다. 이는 dz=가 나오면 인덱싱이 안되는 경우의 수가 있을 수 있다고 판단했다.
코드
// 첫 시도(성공)
const input = require("fs")
.readFileSync(
process.platform === "linux" ? "/dev/stdin" : __dirname + "/example.txt"
)
.toString()
.trim()
.split("\n");
const st = input.shift();
let answer = 0;
let i = 0;
for (i; i < st.length - 2; i++) {
if (st[i] === "c" && (st[i + 1] === "=" || st[i + 1] === "-")) {
answer += 1;
i += 1;
} else if (st[i] === "d") {
if (st[i + 1] === "z" && st[i + 2] === "=") {
answer += 1;
i += 2;
} else if (st[i + 1] === "-") {
answer += 1;
i += 1;
} else answer += 1;
} else if ((st[i] === "l" || st[i] === "n") && st[i + 1] === "j") {
answer += 1;
i += 1;
} else if ((st[i] === "s" || st[i] === "z") && st[i + 1] === "=") {
answer += 1;
i += 1;
} else {
answer += 1;
}
}
if (st.length - i === 2) {
if (st[i] === "c" && (st[i + 1] === "=" || st[i + 1] === "-")) {
answer += 1;
} else if (st[i] === "d") {
if (st[i + 1] === "-") {
answer += 1;
} else answer += 2;
} else if ((st[i] === "l" || st[i] === "n") && st[i + 1] === "j") {
answer += 1;
} else if ((st[i] === "s" || st[i] === "z") && st[i + 1] === "=") {
answer += 1;
} else {
answer += 2;
}
} else if (st.length - i === 1) {
answer += 1;
}
console.log(answer);
두 번째 풀이
두 번째 풀이의 경우는 크로아티아 알파벳들만 길이가 1인 문자로 치환하는 것이다.
코드
const input = require('fs')
.readFileSync(process.platform === 'linux' ? '/dev/stdin' : __dirname + '/example.txt')
.toString().trim().split('\n');
let st = input.shift();
const list = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='];
for (let cro of list) {
st = st.replaceAll(cro, 'q');
}
console.log(st.length);
728x90
'코딩 테스트 > 백준' 카테고리의 다른 글
[JS]1956_운동 (0) | 2025.04.04 |
---|---|
[JS] 2504_괄호의 값 (0) | 2025.03.20 |
[JS] 1976_여행 가자 (0) | 2025.03.18 |
[JS] 8979_올림픽 (0) | 2025.03.15 |
[JS] 최단경로 (0) | 2024.11.28 |