【LeetCode】150. Evaluate Reverse Polish Notation

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/crazy1235/article/details/85983742

Subject

https://leetcode.com/problems/evaluate-reverse-polish-notation/

Explain

https://en.wikipedia.org/wiki/Reverse_Polish_notation

Reverse Polish Notation – RPN
也就是 “逆波兰式” ,又称 “后缀表达式”

如:我们平时写a+b,这是中缀表达式,写成后缀表达式就是:ab+。当然还有前缀表达式+ab。

这道题目的意思就是给定一个运算串,按照后缀表达式的规则计算出最后的结果。


Solution 1

通过栈这种数据结构,当判断到是符号时,从栈中取出两个数值进行运算,然后继续入栈。

// 13ms
public int evalRPN(String[] tokens) {
        if (tokens == null) {
			return 0;
		}
		if (tokens.length == 1) {
			return Integer.parseInt(tokens[0]);
		}
        Stack<String> stack = new Stack<>();
		int result = 0;
		for (int i = 0; i < tokens.length; i++) {
			if (checkTokenValid(tokens[i])) {
				if (stack.size() < 2) {
					result = 0;
					break;
				}
				result = getResultForOneToken(tokens[i], stack.pop(), stack.pop());
				stack.push(Integer.toString(result));
			} else {
				stack.push(tokens[i]);
			}
		}
		return result;
    }
    
    public boolean checkTokenValid(String token) {
		if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
			return true;
		}
		return false;
	}

	public int getResultForOneToken(String token, String rightStr, String leftStr) {
		int left = 0;
		int right = 0;
		try {
			left = Integer.parseInt(leftStr);
			right = Integer.parseInt(rightStr);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		switch (token) {
		case "+":
			return left + right;
		case "-":
			return left - right;
		case "*":
			return left * right;
		case "/":
			return left / right;
		}
		return 0;
	}

End

当然这道题目可以扩展为一个 波兰式 的题目。

猜你喜欢

转载自blog.csdn.net/crazy1235/article/details/85983742