SWEA 1224計算機3



前に解いた2つの問題と何の違いもない.
カッコ演算を考えるだけでいいです.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;

// 3+(4+5)*6+7
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));

		for (int test_case = 1; test_case <= 10; test_case++) {
			StringBuilder sb = new StringBuilder();
			Stack<Character> s = new Stack<>();

			int N = Integer.parseInt(br.readLine());
			st = new StringTokenizer(br.readLine());
			char[] tmp = st.nextToken().toCharArray();
			//
			for (int i = 0; i < N; i++) {
				if (tmp[i] == '+' || tmp[i] == '*' || tmp[i] == '(' || tmp[i] == ')') {
					if (s.isEmpty())
						s.add(tmp[i]);
					else if (tmp[i] == '+') {
						while (!s.isEmpty() && !s.peek().equals('(')) {
							sb.append(s.pop());
						}
						s.add(tmp[i]);
					} else if (tmp[i] == '*') {
						if (s.peek().equals('*')) {
							while (s.isEmpty() || s.peek().equals('+') && !s.peek().equals('(')) {
								sb.append(s.pop());
							}
							s.add(tmp[i]);
						} else {
							s.add(tmp[i]);
						}
					} else if (tmp[i] == '(') {
						s.add(tmp[i]);
					} else if (tmp[i] == ')') {
						while (!s.peek().equals('(')) {
							sb.append(s.pop());
						}
						s.pop();
					}
				} else {
					sb.append(tmp[i]);
				}
			}

			while (!s.isEmpty()) {
				sb.append(s.pop());
			}
			//System.out.println(sb);
			tmp = sb.toString().toCharArray();

			Stack<String> output = new Stack<>();
			for (int i = 0; i < sb.length(); i++) {
				if (tmp[i] != '+' && tmp[i] != '*') {
					output.add(Character.toString(tmp[i]));
				} else {
					if (tmp[i] == '+') {
						int t = Integer.parseInt(output.pop()) + Integer.parseInt(output.pop());
						output.add(Integer.toString(t));
					} else if (tmp[i] == '*') {
						int t = Integer.parseInt(output.pop()) * Integer.parseInt(output.pop());
						output.add(Integer.toString(t));
					}
				}
			}
			bw.append("#" + test_case + " " + output.pop() + "\n");
		}
		bw.flush();
		bw.close();
	}
}