Interviewing algorithms: Using stacks to calculate reversed Polish expressions

Source: Internet
Author: User
Tags stack pop

For a more detailed explanation and code debugging demonstration process, see the video
How to get into Google, algorithm interview skills Comprehensive Promotion guide

Given a string of arithmetic expressions, if the expression satisfies a reverse Polish expression, the string satisfies the following conditions:

1: The expression contains a numeric character or a string of numeric characters.

2: It has a given format, such as "A, B,." ", where A, B is a reversed Polish expression, a period. Represents one of the four operators "+,-, *,/".

For example, the string "3,4,*,1,2,+,+" satisfies the reverse Polish expression, the value of which is: 3 * 4 + (1+2) = 15.

Given a reversed Polish expression, the value of the expression is required to be evaluated.

When dealing with algorithmic problems, choosing the right data structure is equivalent to solving the problem by more than half. The best data structure for dealing with reverse Polish expressions is the stack, the algorithm is as follows:

1, if the current character is a number, then press the number onto the stack.

2, if the current character is an operator, then two elements are popped from the stack, calculated accordingly, and the result is pressed onto the stack

3, when all characters have been processed, the values contained on the stack are the expressions.

Let's go through the algorithm above, based on the given example.
The first character is a numeric character 3, so it presses into the stack:
Char:3
Stack:3

The second character is the number 4, so it presses into the stack
Char:3, 4
Stack:3, 4

The third character is the operator, so it pops up the top two elements of the stack, calculates them, and then presses the result onto the stack:

Char:3, 4, *
Stack:12

The fourth character is a number, so it presses into the stack:
Char:3, 4, *, 1
Stack:12, 1

The fifth character is the number 2, so it presses into the stack:
Char:3, 4, *, 1, 2
Stack:12, 1, 2

The sixth character is an operator, so the two elements at the top of the pop-up stack are calculated accordingly
Char:3, 4, *, 1, 2, +
Stack:12, 3

The seventh character is an operator, so the top two elements of the pop-up stack are computed:
Char:3, 4, *, 1, 2, +, +
Stack:15

By the end of this character processing, the value on the stack of 15 is the result of the expression. Let's look at the corresponding code implementation:

ImportJava.util.Stack; Public  class reversepolishexpr {    PrivateString expression; stack<integer> stack =NewStack<integer> (); Public reversepolishexpr(String expr) { This. expression = expr; } Public int Calculation()throwsException {string[] Exprs = Expression.split (","); for(inti =0; i < exprs.length; i++) {if(Isoperator (exprs[i]) && stack.size () <2) {Throw NewException ("Expression Error"); }if(Isoperator (Exprs[i]))            {docalculation (exprs[i]); }Else{Stack.push (integer.valueof (exprs[i])); }        }returnStack.pop (); }Private Boolean Isoperator(String c) {if(C.equals ("+") ==true|| C.equals ("-") ==true|| C.equals ("*") ==true|| C.equals ("/") ==true) {return true; }return false; }Private void docalculation(String c) {intOP1 = Stack.pop ();intOP2 = Stack.pop ();Switch(c) { Case "+": Stack.push (OP1 + OP2); Break; Case "-": Stack.push (OP1-OP2); Break; Case "*": Stack.push (OP1*OP2); Break; Case "/": Stack.push (OP1/OP2); Break; }    }}

The above code is exactly the algorithm steps described above, we first divide the string containing the comma separated into the corresponding parts, in the for loop to judge, if the encounter is a number, then put it into the stack, if encountered is an operator, then the number from the stack pop, do the corresponding calculation, the calculation results are then pressed into the stack. Finally, let's look at the main entry function:

publicclass StackAndQuque {    publicstaticvoidmain(String[] args) {        new ReversePolishExpr("3,4,*,1,2,+,+");        try {            System.out.println("The result of reverse polish express is " + rp.calculation());        catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

The resulting output from running the above code is:
The result of Reverse Polish Express is 15

That is to say, the result of a given inverse Polish expression is indeed 15, that is, our code should be correct for the implementation of the algorithm.

More technical information, including operating systems, compilers, interview algorithms, machine learning, AI, please take care of my public number:

Interviewing algorithms: Using stacks to calculate reversed Polish expressions

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.