티스토리 뷰

문제는 되게 간단한데, 맞은 사람이 적길래 아 이거, 시간 초과나 메모리 초과가 뜨는 문제겠구나 싶었다.

문제는 그냥 count만큼 for문을 돌리면서, switch문으로 char에 대조해서 cusor값과 stringArray를 조정했다.

const fs = require("fs");

const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let inputChartext = fs.readFileSync(filePath).toString().split("\n");
let inputcharfiltered = inputChartext.filter((value) => value.length > 0);
solution(inputcharfiltered);

function solution(inputArray) {
  let stringArray = Array.from(inputArray[0]);
  const count = +inputArray[1];
  const stringLength = stringArray.length;
  let commandLine = [];
  let cursor = stringLength;

  // console.log(stringArray);
  // console.log(`cursor : ${stringArray[cursor - 1]} 뒤`);
  for (let i = 2; i < count + 2; i++) {
    commandLine = inputArray[i].split(" ");
    switch (commandLine[0]) {
      case "L":
        if (cursor !== 0) {
          cursor--;
          // console.log(
          //   `커서를 왼쪽으로 한 칸 옮김 cursor : ${stringArray[cursor - 1]} 뒤`
          // );
          // console.log(stringArray);
        }
        break;
      case "D":
        if (cursor !== stringLength) {
          cursor++;
          // console.log(
          //   `커서를 오른쪽으로 한 칸 옮김 cursor : ${
          //     stringArray[cursor - 1]
          //   } 뒤`
          // );
          // console.log(stringArray);
        }
        break;
      case "B":
        if (cursor !== 0) {
          // console.log(
          //   `커서 왼쪽의 문자 ${stringArray[cursor - 1]} 삭제. cursor : ${
          //     stringArray[cursor - 2]
          //   } 뒤`
          // );
          stringArray = stringArray.filter((element, index) => {
            return index !== cursor - 1;
          });
          cursor--;
          // console.log(stringArray);
        }
        break;
      case "P":
        stringArray.splice(cursor, 0, commandLine[1]);
        cursor++;
        // console.log(stringArray);
        break;
    }
  }
  console.log(stringArray.join(""));
}

B에서 filter가 문제가 되는 것 같았다.

왜냐면, 없앨 항목은 하나인데 그로인해 filter하는 문자열과 기존 문자열까지... 메모리 초과가 난다면 여기서 나겠단 생각이 들었다. 

하나의 배열로 다 해결하려 하지 말고, 두개의 배열을 stack처럼 사용해보기로 했다.

초기 상태

frontstack이 비어있다면 무시

D에 대해서는 반대로 수행

P $는 frontstack에 값을 push

B는 frontstack이 비어있지 않다면 맨 위의 값을 pop

 

이렇게 구현하면 메모리/시간초과 문제를 모두 해결할 수 있을듯 했다.

 

  for (let i = 2; i < count + 2; i++) {
    commandLine = inputArray[i].split(" ");
    switch (commandLine[0]) {
      case "L":
        if (frontStack.length !== 0) {
          backStack.push(frontStack[frontStack.length - 1]);
          frontStack.pop();
        }
        break;
      case "D":
        if (backStack.length !== 0) {
          frontStack.push(backStack[backStack.length - 1]);
          backStack.pop();
        }
        break;
      case "B":
        if (frontStack.length !== 0) {
          frontStack.pop();
        }
        break;
      case "P":
        frontStack.push(commandLine[1]);
        break;
    }
  }
  console.log(frontStack.join("") + backStack.reverse().join(""));

코드가 정말 간단해졌다.

그리고 backStack의 경우 reverse해주는걸 잊지말기

 

 

 

자료구조를 의식적으로 사용할 수 있을지 고민해보는 습관이 필요하단 생각이 들었던 문제였다.

그리고 시간복잡도를 어떻게 파악할지 잘 모르겠어서 고민중

'■ 알고리즘 > ◻ 백준' 카테고리의 다른 글

[Nodejs]1158번: 요세푸스 문제  (0) 2022.08.03
[Nodejs]10845번: 큐  (0) 2022.08.02
[Nodejs]1874번: 스택 수열  (0) 2022.07.23
[Nodejs]9012번: 괄호  (0) 2022.07.22
[Nodejs]9093번: 단어 뒤집기  (0) 2022.07.20
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함