[算法专题] stack
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的更多相关文章
- [算法专题] LinkedList
前段时间在看一本01年出的旧书<effective Tcp/Ip programming>,这个算法专题中断了几天,现在继续写下去. Introduction 对于单向链表(singly ...
- 【枚举Day1】20170529-2枚举算法专题练习 题目
20170529-2枚举算法专题练习 题解: http://www.cnblogs.com/ljc20020730/p/6918360.html 青岛二中日期 序号 题目名称 输入文件名 输出文件名 ...
- NOIp 图论算法专题总结 (1):最短路、最小生成树、最近公共祖先
系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 最短路 Floyd 基本思路:枚举所有点与点的中点,如果从中点走最短,更新两点间 ...
- NOIp 图论算法专题总结 (2)
系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 树链剖分 https://oi-wiki.org/graph/heavy-lig ...
- NOIp 图论算法专题总结 (3):网络流 & 二分图 简明讲义
系列索引: NOIp 图论算法专题总结 (1) NOIp 图论算法专题总结 (2) NOIp 图论算法专题总结 (3) 网络流 概念 1 容量网络(capacity network)是一个有向图,图的 ...
- ACM&OI 基础数论算法专题
ACM&OI 基础数学算法专题 一.数论基础 质数及其判法 (已完结) 质数的两种筛法 (已完结) 算数基本定理与质因数分解 (已完结) 约数与整除 (已完结) 整除分块 (已完结) 最大公约 ...
- 每周一练 之 数据结构与算法(Stack)
最近公司内部在开始做前端技术的技术分享,每周一个主题的 每周一练,以基础知识为主,感觉挺棒的,跟着团队的大佬们学习和复习一些知识,新人也可以多学习一些知识,也把团队内部学习氛围营造起来. 我接下来会开 ...
- $vjudge-$基本算法专题题解
考完期末又双叒回来刷普及题辣$kk$ 然后放个链接趴还是$QwQ$ [X]$A$ 因为是嘤文($bushi$所以放个题意趴$QwQ$ 就汉诺塔问题,只是说有四个塔$A,B,C,D$,要求输出有1-12 ...
- ACM&OI 基础数学算法专题
[前言] 本人学习了一定时间的算法,主要精力都花在数学类的算法上面 而数学类的算法中,本人的大部分精力也花费在了数论算法上 此类算法相对抽象,证明过程比较复杂 网络上的博客有写得非常好的,但也有写得不 ...
随机推荐
- TP5 自定义验证器
TP内置验证功能提供两种验证方法 验证器(推荐) $validate = Validate::make([ 'id' => 'require|integer', ]); if ($validat ...
- HTTPS协议、TLS协议、证书认证过程解析
一.HTTPS 协议 HTTPS协议其实就是HTTP over TSL,TSL(Transport Layer Security) 传输层安全协议是https协议的核心. TSL可以理解为SSL (S ...
- faster-RCNN框架之rpn 较小目标检测,如果只使用rpn,并减少多个候选框
通常faster-rcnn目标检测有两个步骤,一个是侯选框生成,一个是侯选框微调+目标区分,但是对于单目标识别, 我经常喜欢只使用rpn网络,效果还不错,不过仅仅的rpn使用参考的参数通常会造成一个目 ...
- lambda正则化参数的大小影响
当lambda的值很小时,其惩罚项值不大,还是会出现过拟合现象,当时lambda的值逐渐调大的时候,过拟合现象的程度越来越低,但是当labmda的值超过一个阈值时,就会出现欠拟合现象,因为其惩罚项太大 ...
- Zabbix告警脚本-邮件
[root@iot-svndata02 bin]# cat zbmail.sh #!/bin/bash to_email_address="$1" # 收件人Email地址,zab ...
- 100-days: ten
Title: Emma Watson(艾玛·沃森), Keira Knightley(凯拉·奈特莉) among stars(众多明星之一) urging(竭力主张,呼吁某事) better pro ...
- Python学习之MacBook Pro中PyCharm安装pip以及itchat
前言:Mac中自带的python没有用,自己安装了一个PyCharm,网上很多人说安装Itchat后会安装到自带的Python中去.本文记录怎么安装到自己安装的Python3.7中去.主要技术来源于h ...
- thinkphp5中使用excel导出数据表格(包涵图片)
首先使用composer require phpoffice/phpexcel下载安装phpexcel包. 将包放入extend下面. 不附加图片的导出 /** * 导出excel(不带图片) * @ ...
- MySQL开发——【数据库、数据表的基本操作】
启动MySQL服务器端 CMD启动MySQL服务器端 net start(启动)|stop(停止)|restart(重启)服务名称(mysql) 连接MySQL服务器端 CMD连接MySQL服务器端 ...
- findViewById(R.id.btn_first) 给写成 R.layout.
窗体内放了个按钮, findViewById(R.id.btn_first) 给写成 R.layout. 在java 里边引用结果就是找不到那个id 找了半天找不到原因, 奔着网上常见R找不到的问题, ...