알고리즘/문제

후위 표기식

미케코코 2019. 7. 19. 20:25

문제

대학교를 다니면서 자료구조시간, 기사공부를 하면서 다루어 봤던 내용이다.

이 문제에서 키는 우선순위를 설정하는것이다. (이전에 공부했던 내용을 참고하였다)

1. *  &  /

2. + &  -

3. (

문제에서 예제로 제시가 되었던 ()가 있는경우와 없는경우를 나누어서 생각하였다. 연산자가 아닌 피연산자(문자)가 등장했을때는 String에 저장을 하고 연산자가 등장하였을 때 Stack에 Push를 하였다.

상세 내용은 코드부분에서 Comment를 하였다.

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
import java.util.*;
 
public class Main{
    public static boolean flag=false;
    public static int result=0;
    public static int [] arr;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str=sc.next();
 
        Stack<Character> stack = new Stack<Character>();
 
        String result="";
        //스택에 있는 연산자가 더 크거나 같으면 pop push 
 
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)>='A' && str.charAt(i)<='Z')//피연산자는 result에 그냥 더해줌
            {
                result+=str.charAt(i);
            }
            else
            {
                if(str.charAt(i)=='*' || str.charAt(i)=='/'//+ -보다 우선순위가 높은경우, 같은경우 * / 보다 높은경우 없음
                {
                    while(!stack.isEmpty() && (stack.peek() =='*' || stack.peek()=='/')) //Peek을 하였을 때 (가 있다면 push 없으면 peek pop 
                    {
                        result+=stack.peek();
                        stack.pop();
                    }
                    stack.push(str.charAt(i));
                }
                if(str.charAt(i)=='+'||str.charAt(i)=='-')
                {
                    while(!stack.isEmpty() && stack.peek()!='(')  //( 아닐때 까지 돈다  + - 
                    {
                        result+=stack.peek();
                        stack.pop();
                    }
                    stack.push(str.charAt(i));
                }
                if(str.charAt(i)=='(')//여는 괄호는 그냥 스택에 push 해준다.
                {
                    stack.push(str.charAt(i));
                }
                if(str.charAt(i)==')')
                {
                    while(!stack.isEmpty() && stack.peek()!='('//여기에 if아니잖아...
                    {
                        result+=stack.peek();
                        stack.pop();
                    }
                    stack.pop(); //여기 없으면 ( 계속 존재 무조건 pop해줘야함 
                }
            }
        }
        while(!stack.isEmpty())
        {
            result+=stack.peek();
            stack.pop();
        }
        System.out.println(result);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

https://www.acmicpc.net/problem/1918

 

1918번: 후위 표기식

첫째 줄에 중위 표기식이 주어진다. 단 이 수식의 피연산자는 A~Z의 문자로 이루어지며 수식에서 한 번씩만 등장한다. 그리고 -A+B와 같이 -가 가장 앞에 오거나 AB와 같이 *가 생략되는 등의 수식은 주어지지 않는다. 표기식은 알파벳 대문자와 +, -, *, /, (, )로만 이루어져 있으며, 길이는 100을 넘지 않는다. 

www.acmicpc.net