티스토리 뷰
중위 표기법을 후위 표기법으로 바꾸는 이론에 대해서는 아래 포스팅을 참고하시기 바랍니다.
2019/03/21 - [알고리즘 이론] - [자료구조] 스택으로 후위표기식 구현하기 :: 늦깎이 IT
[소스 코드]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println(convToExpression(str)); } public static String convToExpression(String exp) { Stack<Character> stack = new Stack<>(); int len = exp.length(); String postFix = ""; for (int i = 0; i < len; i++) { char ch = exp.charAt(i); if (ch >= 'A' && ch <= 'Z') { postFix += ch; } else { switch (ch) { case '(': stack.push(ch); break; case ')': while (true) { char pop = stack.pop(); if (pop == '(') break; postFix += pop; } break; case '+': case '-': case '*': case '/': while (!stack.isEmpty() && isProceed(stack.peek(), ch)) postFix += stack.pop(); stack.push(ch); break; } } } while (!stack.isEmpty()) postFix += stack.pop(); return postFix; } // 연산자의 우선순위를 반환하는 메소드 public static int getOpPrec(char op) { switch (op) { case '*': case '/': return 5; case '+': case '-': return 3; case '(': return 1; } return -1; } // op1의 우선순위가 높으면 true, 낮으면 false를 반환 public static boolean isProceed(char op1, char op2) { int op1Prec = getOpPrec(op1); int op2Prec = getOpPrec(op2); if (op1Prec >= op2Prec) return true; else return false; } } | cs |
'알고리즘 문제 > 백준(BOJ)' 카테고리의 다른 글
| [백준 1992번] 쿼드트리 :: 늦깎이 IT (0) | 2019.03.22 |
|---|---|
| [백준 1935번] 후위표기식2 :: 늦깎이 IT (0) | 2019.03.21 |
| [백준 2056번] 작업 :: 늦깎이 IT (0) | 2019.03.20 |
| [백준 1766번] 문제집 :: 늦깎이 IT (0) | 2019.03.19 |
| [백준 2252번] 줄 세우기 :: 늦깎이 IT (0) | 2019.03.19 |
댓글
