구현기/알고리즘 문제풀이

백준 2941 : 크로아티아 알파벳 js 풀이

Sadie Kim 2023. 6. 11. 16:33

문제 링크

다음처럼 풀었다.

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin").toString().trim();

const chroa = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="];

let result = input;

const getChroa = (text, word, count = 0) => {
  if (text.indexOf(word) === -1) {
    result = result.replaceAll(word, "0");
    return count;
  } else if (text.indexOf(word) !== -1) {
    count++;
    return getChroa(text.replace(word, "0"), word, count);
  }
};

const nums = chroa.map((char) => {
  return getChroa(result, char);
});

console.log(
  nums.reduce((acc, cur) => {
    return acc + cur;
  }, 0) + result.split("").filter((a) => isNaN(a)).length
);

근데! 다른 답안 보니까 너무 장황하게 푼 것 같아서... 참고해서 바꿔 봤다.

const fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim();

const chroa = [/c=/g, /c-/g, /dz=/g, /d-/g, /lj/g, /nj/g, /s=/g, /z=/g];

chroa.forEach((char) => {
  input = input.replaceAll(char, 1);
});

console.log(input.length);

만약 로컬 nodejs 환경에서 시험하는데 replaceAll() is not a function 오류가 나온다면 nodejs 버전이 낮아서 생기는 문제다. replaceAll()은 nodejs 15.0.0 버전 이상에서 지원하기 때문에...
덕분에 nodejs lts 버전으로 재설치했다...