백준-Node.js-10828, 스택

송철진·2023년 2월 26일
0

백준-Node.js

목록 보기
37/69

풀이

const fs = require('fs');
const input = fs.readFileSync("/dev/stdin").toString().trim()
                .split('\n').slice(1).map(el => el.split(' '))

class Stack{
  constructor(){
    this.data = [];
    this.index = -1;
  }
  push(value){
    this.index += 1;
    this.data[this.index] = value;
  }
  size(){
    return this.index + 1
  }
  isEmpty(){
    return !this.size() ? 1 : 0
  }
  top(){
    return !this.size() ? -1 : this.data[this.index];
  }
  pop(){
    if(!this.size()){
      return -1
    }else{
      this.index -= 1;
      return this.data.pop();  
    }  
  }
}

const solution = input => {
  let stack = new Stack()
  let obj = {
    'push': (val) => stack.push(val),
    'top': () => stack.top(),
    'pop': () => stack.pop(),
    'size': () => stack.size(),
    'empty': () => stack.isEmpty()
  }
  let result = []
  input.forEach(el => {
    if(el[0] === 'push'){
      obj[el[0]](el[1])
    }else{
      result.push( obj[el[0]]() )
    }
  })
  return result.join('\n') 
}

console.log(solution(input))

스택이니까 stack 클래스를 정의해서 활용하는 방식으로 구현해보았다.
324ms 라서 효율은 별로 안 좋은 편.

다른 풀이

const fs = require('fs');
const input = fs.readFileSync("/dev/stdin").toString().trim()
                .split('\n').slice(1)

const solution = input => {
  let stack = []
  let obj = {
    'push': (val) => stack.push(val),
    'top': () => stack[stack.length-1] || -1,
    'pop': () => stack.pop() || -1,
    'size': () => stack.length,
    'empty': () => stack.length === 0 ? 1 : 0
  }
  let result = []
  
  input.forEach(el => {
    el.startsWith('pu') ?
      obj['push']( el.split(' ')[1] ) : result.push( obj[el]() )
  })
    
  return result.join('\n') 
}

console.log(solution(input))

클래스를 굳이 생성하지 않아도 구현할 수 있다.

profile
검색하고 기록하며 학습하는 백엔드 개발자

0개의 댓글