백준-Node.js-4949, 균형잡힌 세상

송철진·2023년 3월 4일
0

백준-Node.js

목록 보기
45/69

풀이

const fs = require('fs')
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n')
                .map(el => el.replace(/[a-zA-Z0-9. ]/gi, ''))
input.pop()

const solution = (s) => {
  const arr = ['()', '[]'];
  return s.map(el => {
      let i=0;
      while(i<arr.length){	
        if(el.indexOf(arr[i]) !== -1){	
          el = el.split(arr[i]).join("");	
          i=0;	
        }else{
          i++;	
        }
      }
      return el === "" ? 'yes' : 'no';	   
  }).join('\n')
}

console.log(solution(input))

예전에 풀었던 코드카타 괄호 순서 풀이를 재활용했다.

  1. 입력값에 대해 정규표현식으로 괄호를 제외한 나머지 문자열(영대소문자, 숫자, 마침표, 공백)을 빈문자열로 교체하고 마지막줄은 pop()으로 제거한다.

  2. 변환된 입력값의 각 줄을 순회하여 배열 arr의 요소를 기준으로 split, join을 반복한다.

  3. 각줄이 빈문자열이면 균형잡힌 것이므로 yes를, 아니면 no를 반환한다.

stack 으로 풀이

const input = [
'So when I die (the [first] I will see in (heaven) is a score list).',
'[ first in ] ( first out ).',
'Half Moon tonight (At least it is better than no Moon at all].',
'A rope may form )( a trail in a maze.',
'Help( I[m being held prisoner in a fortune cookie factory)].',
'([ (([( [ ] ) ( ) (( ))] )) ]).',
' .',
'.'
]

const solution = input =>{
  let result = '';
  input.map((el, i) => {
    const stack = [];
    if(i === input.length - 1) return;
    
    for(let j = 0; j < el.length; j++) {
      const c = el[j];
      const length = stack.length;
      
      if(c === "(" || c ==="[") {
        stack.push(c);
      } else if(c === ")") {
        length === 0 || stack[length - 1] !== "(" ?
          stack.push(c) : stack.pop();
      } else if(c === "]") {
        length === 0 || stack[length - 1] !== "[" ?
          stack.push(c) : stack.pop();
      }
    }
    stack.length === 0 ? result += "yes\n" : result += "no\n";
  });
  
  return result.substring(0, result.length - 1);
}
console.log(solution(input))

input의 각 요소문자열에 대해 순회하여 해당 문자가

  1. 여는 괄호((,[) 일 때 stack에 추가한다.

  2. 닫는 괄호()) 일 때
    stack의 마지막 값이 여는 괄호(()면 stack의 마지막 값을 삭제한다.
    stack이 비어있거나 stack의 마지막 값이 여는 괄호(()가 아니면 stack에 추가한다.

  3. 닫는 괄호(]) 일 때
    stack의 마지막 값이 여는 괄호([)면 stack의 마지막 값을 삭제한다.
    stack이 비어있거나 stack의 마지막 값이 여는 괄호([)가 아니면 stack에 추가한다.

  4. stack이 비어있으면 yes를, 아니면 no를 result에 추가한다.

substring(), slice() 의 차이
https://hianna.tistory.com/340

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

0개의 댓글