Topic:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
valid operators Are + , -, * , /. Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Solving:
This problem is a classic application of the stack, but also relatively simple, the idea is: hit the number on the stack, encountered the operation symbol on the stack two numbers and then the results into the stack.
Code:
Import Java.util.stack;public class Leetcode150_evaluatereversepolishnotation {/** * @param args */public static void Mai N (string[] args) {//TODO auto-generated method stubstring[] s={"4", "2", "/", "2", "3", "-", "-"}; System.out.println (EVALRPN (s));} public static int Evalrpn (string[] tokens) {int length=tokens.length; stack<integer> stack =new stack<> (); for (int i=0;i<length;i++) {if (!isoperator (tokens[i))) Stack.push (Integer.parseint (tokens[i])); else {int Operanum2=stack.pop (); int Operanum1=stack.pop (), if (Tokens[i].equals ("+")) Stack.push (operanum1+operanum2); else if (Tokens[i].equals ("-")) Stack.push (operanum1-operanum2), Else if (tokens[i].equals ("*")) Stack.push (operanum1* OPERANUM2); else {stack.push (operanum1/operanum2);}} } return Stack.pop (); } public static Boolean isoperator (String s) {if (s.equals ("+") | | S.equals ("-") | | S.equals ("*") | | S.equals ("/")) return true; else return false; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode150 Evaluate Reverse Polish Notation java