본문 바로가기

백준6550 - 부분 문자열 (탐욕법) node.js 본문

개발/algorithm

백준6550 - 부분 문자열 (탐욕법) node.js

자전하는명왕성 2024. 2. 14. 09:34

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

문제는 a,b 두 문자열이 주어졌을 때, b에서 몇 개의 문자를 제거한 뒤 순서를 바꾸지 않고 합쳤을 경우, a가 b의 부분 문자열이 되는지 출력하는 문제다.

 

문제 풀이 방식

a,b 문자열이 존재할 때, 두 개의 포인터를 두어 새로운 문자열을 만든 뒤, 해당 문자열이 짧은 문자열인 a와 일치하는지 확인한 뒤 결과를 리턴하도록 했다.

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

function solution(data) {
  const result = data.map((el) => act(el));
  console.log(result.join("\n"));
}

function act(str) {
  const [a, b] = str.split(" ");

  let left = 0,
    right = 0,
    txt = "";
  while (right < b.length) {
    if (a[left] === b[right]) {
      txt += a[left];
      left++;
    }
    right++;
  }

  return a === txt ? "Yes" : "No";
}

solution(input);
Comments