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 by ["(", "5", "−", "6", ")", "*", "7"]), 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 is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.

代码如下:

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

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

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

return 2

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, pop operands for the operator from stack. Evaluate the operator and push the result back to the stack

3) When the expression is 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 two operands from stack, apply the * operator on 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 two operands from stack, apply the + operator on operands, we get 3 + 2 which results in 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 two operands from stack, apply the – operator on operands, we get 5 – 9 which results in -4. We push the result ‘-4′ to stack. Stack now becomes ‘-4′.

8) There are no more elements to scan, we return the top element from stack (which is the only element left in stack).

即遍历后缀表达式,遇到数字入栈,遇到operator弹栈计算,并将计算结果入栈,当遍历完后缀表达式后,栈顶元素即为返回值。代码如下:

#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(post[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"()[]{}" are all valid but "(]" and "([)]" are not.

class Solution {
public:
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
bool 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 right == ']';
case '{' :
return right == '}';
}
}
};

4

 

[算法专题] stack的更多相关文章

  1. [算法专题] LinkedList

    前段时间在看一本01年出的旧书<effective Tcp/Ip programming>,这个算法专题中断了几天,现在继续写下去. Introduction 对于单向链表(singly ...

  2. 【枚举Day1】20170529-2枚举算法专题练习 题目

    20170529-2枚举算法专题练习 题解: http://www.cnblogs.com/ljc20020730/p/6918360.html 青岛二中日期 序号 题目名称 输入文件名 输出文件名 ...

  3. NOIp 图论算法专题总结 (1):最短路、最小生成树、最近公共祖先

    系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 最短路 Floyd 基本思路:枚举所有点与点的中点,如果从中点走最短,更新两点间 ...

  4. NOIp 图论算法专题总结 (2)

    系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 树链剖分 https://oi-wiki.org/graph/heavy-lig ...

  5. NOIp 图论算法专题总结 (3):网络流 & 二分图 简明讲义

    系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 网络流 概念 1 容量网络(capacity network)是一个有向图,图的 ...

  6. ACM&OI 基础数论算法专题

    ACM&OI 基础数学算法专题 一.数论基础 质数及其判法 (已完结) 质数的两种筛法 (已完结) 算数基本定理与质因数分解 (已完结) 约数与整除 (已完结) 整除分块 (已完结) 最大公约 ...

  7. 每周一练 之 数据结构与算法(Stack)

    最近公司内部在开始做前端技术的技术分享,每周一个主题的 每周一练,以基础知识为主,感觉挺棒的,跟着团队的大佬们学习和复习一些知识,新人也可以多学习一些知识,也把团队内部学习氛围营造起来. 我接下来会开 ...

  8. $vjudge-$基本算法专题题解

    考完期末又双叒回来刷普及题辣$kk$ 然后放个链接趴还是$QwQ$ [X]$A$ 因为是嘤文($bushi$所以放个题意趴$QwQ$ 就汉诺塔问题,只是说有四个塔$A,B,C,D$,要求输出有1-12 ...

  9. ACM&OI 基础数学算法专题

    [前言] 本人学习了一定时间的算法,主要精力都花在数学类的算法上面 而数学类的算法中,本人的大部分精力也花费在了数论算法上 此类算法相对抽象,证明过程比较复杂 网络上的博客有写得非常好的,但也有写得不 ...

随机推荐

  1. win7、centos7 双系统安装总结

    centos7安装过程 问题:TroubleShooting选项进入图形化界面安装才成功. win7恢复引导区 问题:安装完Centos后,win7的引导区不见了 具体恢复过程:http://www. ...

  2. leetcode104

    /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNo ...

  3. leetcode301

    class Solution { public List<String> removeInvalidParentheses(String s) { List<String> a ...

  4. leetcode1028

    class Solution(object): def __init__(self): self.List = list() def rdfs(self,S): if S != '': length ...

  5. String、StringBuffer、StringBuilder区别

    String.StringBuffer.StringBuilder区别 StringBuffer.StringBuilder和String一样,也用来代表字符串.String类是不可变类,任何对Str ...

  6. grains和pillar的联合使用

    在编写sls文件的时候,对于不同的客户端,在配置管理的时候,其安装的环境,配置文件和启动的服务都相同: 如果完全是不同的环境,建议写单独的sls文件,不要混合在一起; 如果是相同的环境,只不过对于不同 ...

  7. 吴裕雄 python深度学习与实践(10)

    import tensorflow as tf input1 = tf.constant(1) print(input1) input2 = tf.Variable(2,tf.int32) print ...

  8. 20162322 朱娅霖 作业011 Hash

    20162322 2017-2018-1 <程序设计与数据结构>第十一周学习总结 教材学习内容总结 哈希方法 一.定义 哈希:次序--更具体来说是项在集合中的位置--由所保存元素值的某个函 ...

  9. php json 写入 mysql 的例子

    $a['aaa']='aaaa'; $a['bbb']='bbb'; $a['ccc']='ccc'; $arr['step_name']='kfkf'; $arr['process_name']=' ...

  10. 针对piix4_smbus ****host smbus controller not enabled的解决方法

    SMBus 目录 SMBus与I2C的差别 SMBus 是 System Management Bus 的缩写,是1995年由Intel提出的,应用于移动PC和桌面PC系统中的低速率通讯.它主要是希望 ...