본문 바로가기
Research/Coding Test

스택/큐_올바른 괄호

by RIEM 2023. 11. 19.

나의 시도 1

function solution(s){

  const stack = [];
  
  s.split('').forEach(chr => {

    stack.push(chr)
    
    while(stack[stack.length-2] + stack[stack.length-1] === "()") {
      stack.pop();
      stack.pop();
    }


  })
  
  return stack.length === 0? true : false
  
}

console.log(solution(")()("	))

코드는 정상 작동하나, 효율성에서 탈락. 아마도 이중 반복문으로 인한 것으로 봉니다.

시도 2

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.array = [];
  }
  
  peek() {
    return this.array[this.array.length - 1];
  }
  
  push(value) {    
    this.array.push(value);
    return this;
  }
  
  pop() {
    this.array.pop();
    return this;
  }
  
  getLength() {
    return this.array.length;
  }
  
  checkCompleteBracket() {
    return this.array[this.array.length-2]==='(' && this.array[this.array.length-1]===')'
  }
}

function solution(s){

  const stack = new Stack();
  
  s.split('').forEach(chr => {

    stack.push(chr)
    
    if (stack.getLength() >= 2) {
      while(stack.checkCompleteBracket()) {
        stack.pop();
        stack.pop();

      }
    }
  })
  return stack.getLength() === 0? true : false
  
}

Stack 클래스를 만들어서 해결했다. 그런데 둘 다 큰 차이는 없는거 같은데.. 왜 첫 번째 시도는 탈락했을까?

'Research > Coding Test' 카테고리의 다른 글

스택/큐_기능개발  (1) 2023.11.19
스택/큐_같은 숫자는 싫어  (1) 2023.11.19
정렬_K번째수  (0) 2023.11.18
해시_전화번호 목록  (0) 2023.11.18
해시_폰켓몬  (0) 2023.11.17

댓글