9012 괄호

송민지·2023년 5월 18일
0

알고리즘

목록 보기
16/22

내가 적은 코드

 function answer() {
     arr1 = [];

  for (let i = 1; i < input.length; i++) {
    for (let j = 1; j < input[i].length; j++)
      input[i][j] == "(" ? arr1.push("(") : arr1.pop(")");

    console.log(arr1.length);
   if (arr1.length === 0) {
     return "Yes";
    } else {
     return "No";
    }
   }
 }
console.log(answer(input[0]));

조금 수정하기는 했는데; 계속 No 만 출력되었다.
콘솔을 찍어보니

'('를 하나씩 빼먹고 있었다;;

한시간동안 끙끙거리다 다른 사람 코드를 살펴 보았다.

다른사람 코드

for(let i = 1; i <= parseInt(inputs[0]); i++){
    const stack = []
    let result = true
    for(let j = 0; j< inputs[i].length; j++){
        if(inputs[i][j] === '(')
            stack.push(inputs[i][j])
        else{
            if(!stack.pop()){
                result = false
            }
        }
    }
    if(stack.length !== 0){
        result = false
    }
        

    if(result == false)
        console.log('NO')
    else
        console.log('YES')
}

차이점

  1. let result = true; 값을 주지 않았다.
  2. arr1.pop()을 할때, arr1의 값이 없는 경우를 설정하지 않았다.
  3. arr1의 값을 0이 아니면 result를 변경하는것을 생각하지 않았다.
  4. 첫 for문을 돌릴때 6보다 작거나 같아야 했었는데, 그 점을 생각하지 못했다.

알고리즘은 풀때마다 내가 바보인가 싶은 느낌을 들게한다.. 흑 ..


[백준/node.js] 9012번 괄호

profile
기록하는 일상

0개의 댓글