Algorithm/문제

baekjoon. 후위 표기식

Yuclid 2021. 6. 1. 15:56

문제

문제

풀이

스택을 이용해서 풀 수 있는 문제

각 연산자에 우선 순위를 두고 그 순위에 따라서 연산자를 뺄지 넣을지 결정한다

연산자가 아닌 피연산자는 바로 문자열에 넣는다

순위의 경우에는 * / 가 우선 + - 순서

a+b*c의 경우에는

+ b * c  
a        
b * c    
a        
 
 
 
+
* c      
a b      
 
 
 
+
c        
a b      
 
 
*
+
a b c    
 
 
*
+

수식을 다 담고 스택에 남은 연산자는 문자열에 위에서 부터 순서대로 추가해준다

a b c * +

코드

    // const readline = require('readline');
    //
    // const rl = readline.createInterface({
    //     input: process.stdin,
    //     output: process.stdout
    // });
    // let input = ''
    // rl.on('line', function(line) {
    //     input += line+'\n';
    // }).on('close',function (){
    //     solution(input.slice(0,-1))
    //     process.exit();
    // });

    function checkChar(char){
        const map = new Map();
        map.set('*',3);
        map.set('/',3);
        map.set('(',1);
        map.set(')',1);
        map.set('+',2);
        map.set('-',2);

        return map.get(char)||0;
    }

    function solution(input){
        const temp = input.split('');
        const stack = [];
        let answer = '';

        for (let i = 0; i < temp.length; i++) {
            const char = temp[i];
            const value = checkChar(char);
            if(value){
                if(!stack.length){
                    stack.push(char);   
                }
                if(value>=2){
                    while (stack.length && checkChar(stack[stack.length-1])>=value){
                        answer+=stack.pop();
                    }
                    stack.push(char);
                    continue;
                }
                if(char==='('){
                    stack.push(char);
                    continue;
                }
                if(char===')'){
                    while (stack.length&&stack[stack.length-1]!=='('){
                        answer+=stack.pop();
                    }
                    stack.pop();
                    continue;
                }
                continue;
            }
            answer+=char;
        }
        while (stack.length){
            answer+=stack.pop();
        }
        console.log(answer)
    }