- Published on
 
알고리즘 백준- 10828 스택
- Authors
 
- Name
 - Kevin Junho Kim
 
10828 스택
https://www.acmicpc.net/problem/10828
- JS
첫번째 시도: 시간초과, console.log는 시간이 많이걸리니 적게 사용해야한다.
두번째 시도 ✅: 배열.join을 이용해 출력
var input = require('fs').readFileSync('/dev/stdin').toString().split('\n')
function CreateStack(input) {
  const stack = []
  const answer = []
  const commands = {
    push: (data) => {
      stack.push(data[1])
    },
    pop: () => {
      return stack.length > 0 ? stack.pop() : -1
    },
    size: () => {
      return stack.length
    },
    empty: () => {
      return stack.length === 0 ? 1 : 0
    },
    top: () => {
      return stack.length > 0 ? stack[stack.length - 1] : -1
    },
  }
  for (let i = 0; i < input.length; ++i) {
    const data = input[i].trim().split(' ')
    const command = data[0]
    if (commands[command]) {
      const result = commands[command](data)
      if (result !== undefined) {
        answer.push(result)
      }
    }
  }
  console.log(answer.join('\n'))
}
CreateStack(input)
반복문인 for loop만 input의 길이만큼 (n번) 반복되고 나머지는 그냥 상수 계산이기 때문에
시간 복잡도는 O(n) 이다.
- Python
import sys
n = int(sys.stdin.readline())
stack = []
for i in range(n):
    command = sys.stdin.readline().split()
    if command[0] == 'push':
        stack.append(command[1])
    elif command[0]  == 'pop':
        if not stack:
            print(-1)
        else:
            print(stack.pop())
    elif command[0] == 'size':
        print(len(stack))
    elif command[0] == 'empty':
        print(int(len(stack) == 0))
    elif command[0] == 'top':
        if not stack:
            print(-1)
        else:
            print(stack[-1])
역시 반복문인 for loop만 input의 길이만큼 (n번) 반복되고 나머지는 그냥 상수 계산이기 때문에
시간 복잡도는 O(n) 이다.
자바스크립트 vs 파이썬
| 메모리 | 시간 | 언어 | 코드 길이 | 
|---|---|---|---|
| 31120 | 48 | Python 3 / 수정 | 538 | 
| 12516 | 200 | node.js / 수정 | 843 |