[BOJ] 1918번: 후위 표기식

HyeRyun·2020년 10월 29일
0

Baekjoon Online Judge

목록 보기
3/30
post-thumbnail

✔️ 문제

😎 소스 코드

#include <iostream>
#include <stack>
#include <cstring>

using namespace std;

int checkOperator(char s) {
  int priority = 0;
  
  if (s == '*' || s == '/') {
    priority = 3;
  } else if (s == '+' || s == '-') {
    priority = 2;
  } else if (s == '('){
    priority = 1;
  } else {
    priority = -1;
  }
  
  return priority;
}

void toPostfix(string str) {
  string answer;
  stack<char> s;
  
  for (int i = 0; i < str.length(); ++i) {
    char ch = str[i];
    switch (ch) {
      case '+':
      case '-':
      case '*':
      case '/':
        while (!s.empty() && (checkOperator(ch) <= checkOperator(s.top()))){
          if (s.top() == '('){
            s.pop();
          } else {
            answer += s.top();
            s.pop();
          }
        }
        s.push(ch);
        break;
      case '(':
        s.push(ch);
        break;
      case ')':
        while (s.top() != '(') {
          answer += s.top();
          s.pop();
        }
        s.pop(); // '(' pop해줌
        break;
      default:
        // alphabet
        answer += ch;
        break;
    }
  }
  
  // 스택에 뭔가가 남아있을때: 다 빼준다
  while (!s.empty()){
    if (s.top() == '('){
      s.pop();
    } else {
      answer += s.top();
      s.pop();
    }
  }
    
  cout << answer << endl;
}

int main(){
  string input;
  cin >> input;
  
  toPostfix(input);
  
  return 0;
}

✊ 문제를 풀고 나서

최근에 코딩 테스트를 봤다가 충격먹고...
기초부터 다시 해보기로 결심하고 스택을 풀었다...
자괴감 max
백준 사이트는 그냥 c++로 푸는게 마음 편할 것 같다.


후위 표기식 변환에서 가장 중요한 점을 꼽자면,

  1. 연산자에 우선순위를 두는 것
  2. 스택에 연산자를 푸쉬할 때 스택 탑과 비교해서 적절히 팝하고 푸쉬하는 것

이 정도인 것 같다.

profile
개발개발

0개의 댓글