웹개발/코딩 테스트 문제 & 풀이

[코딩 테스트 문제 + 풀이] Stacks and Queues, Leader

데브리 2021. 11. 6. 04:35

 

Stacks and Queues

 

 

Q. Brackets "[({})]"

 


stack.push("[")
stack.push("(")
stack.push("{")
stack.pop() == "{" ?
stack.pop() == "(" ?
stack.pop() == "[" ?
stack.empty?

 

 

function solution(S) {
  let stack = [];
  for (const c of S) {
      if (c === '{' || c === '[' || c === '(') {
          stack.push(c);
      } else if (c === '}') {
          if (stack.length === 0 || stack.pop() !== '{') return 0;
      } else if (c === ']') {
          if (stack.length === 0 || stack.pop() !== '[') return 0;
      } else if (c === ')') {
         if (stack.length === 0 || stack.pop() !== '(') return 0;
      }
  }
  return stack.length ? 0 : 1;
}

console.log(solution("(){}{}[]{}"));

 

 

 

 

 

Q. Fish

 

function solution(A, B) {
  let stack = [];
  let survivors = 0;
  for (let i = 0; i < A.length; i++) {
    let weight = A[i];
    if (B[i] === 1) {
      stack.push(weight);
    } else {
      let weightDown = stack.length === 0 ? -1 : stack.pop();
      while (weightDown !== -1 && weightDown < weight)
        weightDown = stack.length === 0. ? -1 : stack.pop();
      if (weightDown === -1)
        survivors += 1;
      else
        stack.push(weightDown);
    }
  }
  return survivors + stack.length;
}


console.log(solution([4, 8, 2, 6, 7], [0, 1, 1, 0 ,0]));  // 2

 

 

 

 

 

 

Q. Leader

 

function solution(A) {
  let consecutiveSize = 0;
  let candidate = 0;
  A.forEach(item => {
    if(consecutiveSize === 0) {
      candidate = item;
      consecutiveSize += 1;
    } else if (candidate === item) {
      consecutiveSize += 1;
    } else {
      consecutiveSize -= 1;
    }
  });
  let occurrence = 0;
  let index = 0;
  for (let i = 0; i < A.length; i++) {
    if (A[i] === candidate) {
      occurrence++;
      index = i;
    }
  }
  return occurrence > A.length / 2.0 ? index: -1;
}

console.log(solution([3, 0, 1, 1, 4, 1, 1]));