백준 1918 C++

Date:     Updated:

카테고리:

태그:

백준 1918

설명할 게 없는 문제다.

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	stack<char> oper;
	string s;
	cin >> s;
	for (int x = 0; x < s.length(); x++) {
		if (s[x] >= 'A' && s[x] <= 'Z') cout << s[x];//A~Z는 그냥 계속 push하기.
		else 
		{
			if (s[x] == '(')oper.push(s[x]);//'('일 경우에 그냥 스택에 쌓아놓기(괄호)
			else if (s[x] == '*' || s[x] == '/') {//*나 /일 경우에
				while (!oper.empty() && (oper.top() == '*' || oper.top() == '/')) {//맨 위에 있는게 같은 *나 /면 앞선 순서대로 계산하니까 
					cout << oper.top();//방출
					oper.pop();
				}
				oper.push(s[x]);//넣기.
			}
			else if (s[x] == '+' || s[x] == '-') {//들어오는게 +나 -라면 
				while (!oper.empty() && oper.top() != '(') {//괄호로 묶여서 처리하는게 아니면 방출. 
					cout << oper.top();
					oper.pop();
				}
				oper.push(s[x]);
			}
			else if (s[x] == ')') {//괄호를 닫으면
				while (!oper.empty() && oper.top() != '(') {//그 안에 있는거는 그 괄호의 시작일떄까지.
					cout << oper.top();//방출.
					oper.pop();
				}
				oper.pop();//(도 방출하기. 
			}

		}
	}
	while (!oper.empty()) {//남아있는 것들 방출. 
		cout << oper.top();
		oper.pop();
	}
	return 0;
}

BOJ 카테고리 내 다른 글 보러가기

댓글 남기기