Evaluate Reverse Polish Notation

public class Solution {

		public int evalRPN(String[] tokens) {
			Stack<Integer> s = new Stack<>();
			String operations = "+-*/";
			for (String token : tokens) {
				if (!operations.contains(token)) {
					s.push(Integer.valueOf(token));
				} else {
					// 一般pop需要判断是否为空
					int a = s.pop();
					int b = s.pop(); //a为先出栈的数,b为后出栈的数
					int res;
					if (token.equals("+")) {
						res = b + a;
						s.push(res);
					}
					if (token.equals("-")) {
						res = b - a;
						s.push(res);
					}
					if (token.equals("*")) {
						res = b * a;
						s.push(res);
					}
					if (token.equals("/")) {
						res = b / a;
						s.push(res);
					}
				}
			}
			return s.pop();
		}
}

最后更新于

这有帮助吗?