Evaluate Reverse Polish Notation, evaluatenotation

Source: Internet
Author: User

Evaluate Reverse Polish Notation, evaluatenotation

Original question link: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

Question: Give the inverse Polish style and then ask for the result.

Solution: Single stack

Idea: traverse the inverse Polish formula. If it is a number, it is written into the stack. If it is an operator, two elements at the top of the stack will pop up, and then the result of the corresponding operator will be written into the stack. After the traversal is complete, the elements in the stack are the desired results.

Time Complexity: O (N) space complexity: O (1)

class Solution {public:    int evalRPN(vector<string> &tokens) {        if(tokens.empty())            return 0;        stack<int> s;        int op1=0,op2=0;        for(int i=0;i<tokens.size();i++)        {            if(tokens[i]=="+")            {                op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1+op2);            }            else if(tokens[i]=="-")            {                op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1-op2);            }            else if(tokens[i]=="*")            {                op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1*op2);            }            else if(tokens[i]=="/")            {                op2=s.top();s.pop();op1=s.top();s.pop();s.push(op1/op2);            }            else                s.push(atoi(tokens[i].c_str()));        }        return s.top();    }};


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.