[Algorithmic topic] stack

Source: Internet
Author: User
Tags lintcode

1. Convert Expression to Reverse Polish Notation

http://www.lintcode.com/en/problem/convert-expression-to-polish-notation/

Given An expression string array, return the Polish notation of this expression. (Remove the parentheses)

Example

For the expression [(5.6) * 7] (which represented ["(", "5", "?", "6", ")", "*", "7"] by), the corresponding Polish notation is [*-5 6 7] (which the return value should be ["*", "?", "5", "6", "7"] ).

algorithm
1. Scan the infix expression from left to right.
2. If The scanned character is an operand, output it.
3. Else,
..... 3.1 If The precedence of the scanned operator is greater than the precedence of the operator in the stack (or the Stack is empty), push it.
..... 3.2 Else, Pop the operator from the stack until the precedence of the scanned operator are less-equal to the Prece Dence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If The scanned character is a ' (', push it to the stack.
5. If The scanned character is a ') ', pop and output from the stack until a ' (' is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it's not empty.

The code is as follows:

Class Solution {public:/** * @param expression:a string array * @return: The Reverse Polish notation of this        Expression */vector<string> Converttorpn (vector<string> &exp) {vector<string> VEC;                Stack<string> St;            for (int ix = 0; IX! = Exp.size (); ix++) {if (IsDigit (Exp[ix])) {vec.push_back (Exp[ix]);            } else if (exp[ix] = = "(") {St.push (Exp[ix]);                    } else if (exp[ix] = = ")") {while (St.top ()! = "(") {Vec.push_back (St.top ());                St.pop (); } st.pop ();                    Pop "("} else {while (!st.empty () && pri (Exp[ix]) <= pri (St.top ())) {                    Vec.push_back (St.top ());                St.pop ();            } st.push (Exp[ix]); }} while (!st.empty ()) {Vec.Push_back (St.top ());        St.pop ();    } return VEC;        } private:int isdigit (const string &s) {size_t len = s.size ();        String start (len, ' 0 ');        String end (Len, ' 9 ');    Return start <= s && s <= end;        } int pri (const string &s) {if (s = = "+" | | s = = "-") {return 1;        } else if (s = = "*" | | s = = "/") {return 2;    } return-1; }};
2. Expression Evaluation

http://www.lintcode.com/en/problem/expression-evaluation/#

Given An expression string array, return the final result of this expression

Example

2*6-(23+7)/(1+2)for the expression, input is

[  "2", "*", "6", "-", "(",  "23", "+", "7", ")", "/",  (", "1", "+", "2", ")"],

Return2

Following is algorithm for evaluation postfix expressions.
1) Create a stack to store operands (or values).
2) Scan The given expression and do following for every scanned element.
... a) If the element is a number, push it into the stack
... b) If the element is a operator, pops operands for the operator from stack. Evaluate the operator and push the result back to the stack
3) When the expression was ended, the number in the stack is the final answer

Example:
Let the given expression be "2 3 1 * + 9-". We Scan all elements-one by one.
1) Scan ' 2 ', it s a number, so push it to stack. Stack contains ' 2 '
2) Scan ' 3 ', again a number, push it to stack, stack now contains ' 2 3′ (from bottom to top)
3) Scan ' 1 ', again a number, push it to stack, stack now contains ' 2 3 1′
4) Scan ' * ', it's an operator, pop-operands from stack, apply the * operator to operands, we get 3*1 which results in 3. We Push the result ' 3 ' to stack. Stack now becomes ' 2 3′.
5) Scan ' + ', it's an operator, Pop II operands from stack, apply the + operator on operands, we get 3 + 2 which results I N 5. We Push the result ' 5 ' to stack. Stack now becomes ' 5 '.
6) Scan ' 9 ', it ' s a number, we push it to the stack. Stack now becomes ' 5 9′.
7) Scan '-', it ' s an operator, Pop II operands from stack, apply the–operator on operands, we get 5–9 which results I N-4. We Push the result ' -4′to stack. Stack now becomes ' -4′.
8) There is no more elements to scan, we return the top element from the stack (which is the only element of the left in stack).

That is, traversing the suffix expression, encountering the number into the stack, encountering operator stack calculation, and the calculation results into the stack, when the suffix expression is traversed, the top element of the stack is the return value. The code is as follows:

#include <stdlib.h>class Solution {public:/** * @param expression:a vector of strings;            * @return: an integer */int evaluateexpression (vector<string> &exp) {if (Exp.empty ()) {        return 0;        } vector<string> post = CONVERTTORPN (exp);        Stack<int> St; for (int ix = 0; IX! = Post.size (); ix++) {if (IsDigit (Post[ix])) {St.push (Atoi (PO            St[ix].c_str ()));                    } else {int right = St.top (); St.pop (); int left = St.top ();                    St.pop ();                    int res = calculate (left, right, Post[ix]);                            St.push (RES);    }} return St.top ();            } private:int Calculate (int left, int. right, const string &oper) {if (oper = = "+") {        return left + right;  } else if (oper = = "-") {return left-right;      } else if (oper = = "*") {return left * right;        } else {return left/right;        }} vector<string> Converttorpn (vector<string> &exp) {vector<string> VEC;                Stack<string> St;            for (int ix = 0; IX! = Exp.size (); ix++) {if (IsDigit (Exp[ix])) {vec.push_back (Exp[ix]);            } else if (exp[ix] = = "(") {St.push (Exp[ix]);                    } else if (exp[ix] = = ")") {while (St.top ()! = "(") {Vec.push_back (St.top ());                St.pop (); } st.pop ();                    Pop "("} else {while (!st.empty () && pri (Exp[ix]) <= pri (St.top ())) {                    Vec.push_back (St.top ());                St.pop ();            } st.push (Exp[ix]); }} while (!st.empty ()) {Vec.push_back (St.top ());        St.pop ();    } return VEC;        } int IsDigit (const string &s) {size_t len = s.size ();        String start (len, ' 0 ');        String end (Len, ' 9 ');    Return start <= s && s <= end;        } int pri (const string &s) {if (s = = "+" | | s = = "-") {return 1;        } else if (s = = "*" | | s = = "/") {return 2;    } return-1; }};
3. Valid parentheses

http://www.lintcode.com/en/problem/valid-parentheses/#

Given A string containing just the characters ‘(‘, ‘)‘ , ‘{‘ , ‘}‘ , ‘[‘ and ‘]‘ , determine if the input string is valid.

Example

The brackets must close in the correct order, and is all valid but and is not "()" "()[]{}" "(]" "([)]" .

Class Solution {public:/** * @param s a String * @return whether the string is a valid parentheses */b        Ool isvalidparentheses (string& s) {stack<char> st;                for (String::const_iterator ITR = S.begin (); ITR! = S.end (); itr++) {if (St.empty ()) {            St.push (*ITR);            } else if (consist (St.top (), *itr)) {St.pop ();            } else {St.push (*ITR);    }} return St.empty ();                 } Private:bool consist (const char left, const CHAR-right) {switch (left) {case ' (':            return right = = ') ';            Case ' [': return to right = = '] ';        Case ' {': return to right = = '} '; }    }};

4

[Algorithmic topic] stack

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.