백준

1918 후위 표기식

거북이같은곰 2021. 9. 30. 01:36


https://www.acmicpc.net/board/view/75399

 

글 읽기 - 이거 문제가 이상해요 36%를 넘길 수 없어요.[내공100

댓글을 작성하려면 로그인해야 합니다.

www.acmicpc.net

https://www.acmicpc.net/board/view/63719

 

글 읽기 - emptystack 런타임 에러궁금합니다

댓글을 작성하려면 로그인해야 합니다.

www.acmicpc.net

https://summer-story.tistory.com/13

 

[Stack] 백준 1918번: 후위 표기식

 이번에는 백준 스택 문제를 풀면서 꽤 중요하다고 생각한 1918번 후위표기식에 대해 알아보자! (ت) 후위 표기식이란?  문제에 나와있지만, 한번 더 설명을 하자면 우리는 a+b나 a*b+(c-d)와 같은

summer-story.tistory.com

 

 

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
	static Stack<String> stk = new Stack<String>();
	public static void main(String[] args) throws NumberFormatException, IOException {
		System.out.println(InToPost("A+B*C-D/E"));
	}
	static String InToPost(String infixString) {
		String postfixString = "";
		
		for(int index = 0; index < infixString.length(); ++index) {
			char chValue = infixString.charAt(index);
			if(chValue == '(') {
				stk.push("(");
			}
			else if(chValue == ')') {
				String oper = stk.peek();
				while(!stk.peek().equals("(")) {
					postfixString += stk.peek();
					stk.pop();
				}
					stk.pop();
			}
			else if (chValue == '+' || chValue == '-') {
				if(stk.empty()) {
					stk.push(chValue + "");
				}
				else {
					while(!stk.empty()) {
						if(stk.peek().equals("("))
							break;
							postfixString += stk.peek();
							stk.pop();
					}
					stk.push(chValue + "");
				}
			}
			else if(chValue == '*' || chValue == '/') {
				if(stk.empty()) {
					stk.push(chValue + "");
				}
				else {
					if(stk.peek().equals("*") || stk.peek().equals("/")) {
						postfixString += stk.peek();
						stk.pop();
					}
					stk.push(chValue + "");
				}
			}
			else {
				postfixString += chValue;
			}
		}
		while(!stk.empty()) {
			String oper = stk.peek();
				stk.pop();
				postfixString += oper;
		}
		return postfixString;
	}
}