본문 바로가기

백준1213 - 펠린드롬 만들기 node.js 본문

개발/algorithm

백준1213 - 펠린드롬 만들기 node.js

자전하는명왕성 2023. 12. 21. 09:55

https://www.acmicpc.net/problem/1213

해당 문제는 좌우 대칭이 같은 문자열을 출력하는 펠린드롬 문제다. 

 

문제 해결 방식

먼저 테이블에 각각의 알파벳의 갯수를 담은 뒤, 홀수의 수를 가진 알파벳이 두 개 이상이라면 펠린드롬을 만들 수 없기 때문에 실패 메세지를 출력했다. 만약 알파벳이 홀수인 경우가 없거나 하나만 존재한다면 펠린드롬을 만들 수 있는 경우이므로 먼저 정렬을 취한 뒤 앞 문자열을 생성하고 이를 반전시켜 문제를 풀이할 수 있었다.

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "입력.txt")
  .toString()
  .trim()
  .split("\n");

function solution(data) {
  const str = data[0].split("");
  const table = {};
  str.forEach((el) => (table[el] = (table[el] || 0) + 1));

  const entries = Object.entries(table).sort((a, b) =>
    a[0].localeCompare(b[0])
  );

  let oddCnt = 0;
  let mid = "";
  for (let i = 0; i < entries.length; i++) {
    const [s, n] = entries[i];
    if (n % 2 == 1) {
      oddCnt++;
      mid = s;

      if (oddCnt >= 2) {
        console.log("I'm Sorry Hansoo");
        return;
      }
    }
  }

  let front = "";
  entries.forEach(([s, n]) => {
    front += s.repeat(Math.floor(n / 2));
  });
  let back = front.split("").reverse().join("");
  console.log(front + mid + back);
}

solution(input);
Comments