[SEB_FE] Stack & Queue

seunghyo·2023년 5월 10일
0

SEB_FE

목록 보기
29/38
post-thumbnail

Stack ) 🧩유효한 괄호쌍 문제🧩

입력된 괄호 값들이 모두 쌍이 맞게 올바른지를 판단해 모두 쌍이 맞으면 true 그렇지 않으면 false를 출력


📍Testcase

const result1 = isValid('[]');
console.log(result1); // true

const result2 = isValid('[)');
console.log(result2); // false

const result3 = isValid('[]{}()');
console.log(result3); // true

const result4 = isValid('[]{)()');
console.log(result4); // false

📍code


const isValid = (str) => {

  /*str 검사하기
  1. if 열린 괄호 쌍({[이 들어올 경우 => 새로운 괄호의 시작이므로 일단 저장.
  2. if 닫힌 괄호쌍이 들어올 경우 => 그 앞이 열린 괄호쌍인지 확인해야함 => 그 앞의 짝이 맞으면 true 아님 false
  3. 그 외의 것이 들어올 경우 => false
  */

  let result = true; //결과값
  let stack = []; //열린 괄호가 들어갈 스택
  let pair = {
    '[':']','(':')','{':'}'
  }
  if(str.length === 0 || str.length % 2 !== 0){return false;}
  // str 길이가 0이거나 , 짝수 값이 아니면 괄호짝이 맞지않음. 
  for(let i = 0; i < str.length; i++){
    if(str[i] === '['||str[i] === '('||str[i] === '{'){
      stack.push(str[i]);//스택에 집어넣어줌.
    }
    else{
      let pair_key = stack.pop();
      if(str[i] !== pair[pair_key]){
        result = false;
      }
    }
  }
  if(stack.length !== 0){result = false;}
  return result;
}

3가지 경우로 생각해보았는데 3번째 경우에서 에러가 났다. 그래서 열린 괄호 일때와 아닐때로 나누어 조건문을 작성했다(이건 됨..) 바로 return false해서 나온 에러인가...그것을 고치고 바로 pair키와 비교하는 조건문 하나 더 넣어주었다. 스택에 열린 괄호가 남아있다면 그것도 false로 처리하도록 하여 마지막 조건까지 통과되었다!:)

Queue ) 🧩박스 포장 문제🧩

  • 들어온 순서대로 한 명씩 나가야 합니다.
  • 뒷사람이 포장을 전부 끝냈어도 앞사람이 끝내지 못하면 기다려야 합니다.
  • 한꺼번에 나갈 수 있는 사람의 최대 수를 구해야합니다.

📍Testcase

const boxes = [5, 1, 4, 6];
const output = paveBox(boxes);
console.log(output); // 3

const boxes2 = [1, 5, 7, 9];
const output2 = paveBox(boxes2);
console.log(output2); // 1

📍code

function paveBox(boxes) {
  // TODO: 여기에 코드를 작성합니다.
  /* Queue
    boxes 배열 ( 0번 인덱스 부터 ~ 0번 인덱스에 해당하는 값보다 큰 값(n번인덱스)을 만나기전까지)
   */ 
  let findmax = [];
  while(boxes.length > 0){
    let nidx = boxes.findIndex(i => i > boxes[0]);
    if(nidx === -1){
      findmax.push(boxes.length);
      boxes.splice(0,boxes.length);
    }
    else{
      findmax.push(nidx);
      boxes.splice(0,nidx);
    }
  }
  return Math.max(...findmax);
}

0개의 댓글