[백준 2504번] 구현 - 괄호의 값

김민지·2023년 5월 15일
0

냅다 시작 백준

목록 보기
43/118

✨ 문제 ✨

어렵다 어렵다 어렵다.

✨ 정답 ✨

const fs = require("fs");
const { SourceTextModule } = require("vm");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./예제.txt";
let input = fs.readFileSync(filePath).toString().trim();

// const fs = require('fs'); 
// let input = fs.readFileSync('/dev/stdin').toString().trim();

const isNormal=(str)=>{
    const stack=[];
    for (let i=0;i<str.length;i++){
        let top=stack[stack.length-1];
        let current=str[i];
        if (current===']' && top==='['){
            stack.pop();
        }else if (current===')' && top==='('){
            stack.pop();
        }else{
            stack.push(current);
        }
    }
    return stack.length?false:true;

}

const solution=(string)=>{
    let stack=[];
    if(!isNormal(string)){
        return 0;
    }

    for (let i=0;i<string.length;i++){
        let top=stack[stack.length-1];
        const current =string[i];
        if (current==='(' || current ==='['){
            stack.push(current);
        }else if (current===')' || current===']'){
            let open=current===')' ? '(': '[';
            let point=open==='('? 2 : 3;

            if (top===open){
                stack.pop();
                stack.push(point);
            }else{
                let temp=0;
                while(true){
                    const pop=stack.pop();
                    if (typeof pop==='number'){
                        temp+=pop;
                    }else if (pop===open){
                        stack.push(temp*point);
                        break;
                    }
                }
                
            }

        }

    }
    return stack.reduce((num1, num2)=>num1+num2);
}

const answer=solution(input);
console.log(answer)

🧵 참고한 정답지 🧵

https://junghyeonsu.tistory.com/252

💡💡 기억해야 할 점 💡💡

배열을 사용한다면 배열 요소를 차례대로 분류할 생각을 하는 것이 좋은 것 같다.

profile
이건 대체 어떻게 만든 거지?

0개의 댓글