Evaluate Reverse Polish Notation--leetcode

Source: Internet
Author: User

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators is + , - , * , / . Each operand is an integer or another expression.

Some Examples:

  ["2", "1", "+", "3", "*")--((2 + 1) (3)-9  ["4", "", "5", "/", "+"], 4 + (13/5))

Given a string array, the data is a suffix expression that evaluates the value of the expression.

Problem-solving ideas: With the stack to save the operand, encountered the number on the stack, encountered the operator from the stack to take out two elements of the operation and then into the stack, the last stack only one element is the result. It's easier to do this without parentheses, directly on the code.

  StaticMap<string, integer> op =NewHashmap<>(); Static{op.put ("+", 1); Op.put ("-", 2); Op.put ("*", 3); Op.put ("/", 4); }     Public intEVALRPN (string[] tokens) {if(Tokens = =NULL|| Tokens.length = = 0) {            return0; } Stack<Integer> nums =NewStack<>();  for(String s:tokens) {if(Op.get (s)! =NULL) {                intFA =Nums.pop (); intFB =Nums.pop (); if(Op.get (s) = = 1) {Nums.push (FB+FA); } Else if(Op.get (s) = = 2) {Nums.push (FB-FA); } Else if(Op.get (s) = = 3) {Nums.push (FB*FA); } Else{Nums.push (FB/FA); }            } Else{Nums.push (integer.valueof (s)); }        }        returnNums.peek (); }

Evaluate Reverse Polish Notation--leetcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.