[算法专题] 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 基础数学算法专题
[前言] 本人学习了一定时间的算法,主要精力都花在数学类的算法上面 而数学类的算法中,本人的大部分精力也花费在了数论算法上 此类算法相对抽象,证明过程比较复杂 网络上的博客有写得非常好的,但也有写得不 ...
随机推荐
- Innodb锁相关总结
一.InnoDB共有七种类型的锁: (1)共享/排它锁(Shared and Exclusive Locks) (2)意向锁(Intention Locks) (3)插入意向锁(Insert Inte ...
- 学习node.js 第2篇 介绍node.js 安装
Node.js - 环境安装配置 如果愿意安装设置Node.js环境,需要计算机上提供以下两个软件: 一.文本编辑器 二.Node.js二进制安装包 文本编辑器 这将用来编写程序代码. 一些编辑器包括 ...
- Linux命令:mapfile
mapfile [-n 计数] [-O 起始序号] [-s 计数] [-t] [-u fd] [-C 回调] [-c 量子] [数组] 两个作用: 一是给index数组读取标准输入来赋值:二是文件描述 ...
- combox省市县三级联动
/** * Name 获取省份(初始化) */ function showProvince(id1, id2, id3) { var paramData = {}; $.ajax({ url: osp ...
- MyBatis :Insert (返回主键、批量插入)
一.前言 数据库操作怎能少了INSERT操作呢?下面记录MyBatis关于INSERT操作的笔记,以便日后查阅. 二.insert元素 属性详解 其属性如下: parameterType , ...
- linux 部分常用命令
1.Linux 删除除了某个文件之外的所有文件 [root@localhost abc]# ls |grep -v 'a' |xargs rm -f 其中rm -f !(a) 最为方便.如果保留a和 ...
- sqlserver truncate清空表时候,无法删除 'B表',因为该表正由一个 FOREIGN KEY 约束引用。
外键: 查询:select object_name(a.parent_object_id) 'tables' from sys.foreign_keys a where a.referenced_ ...
- init.d目录下的文件定义
init.d目录下存放的一些脚本一般是linux系统设定的一些服务的启动脚本. 系统在安装时装了好多服务,这里面就有很多对应的脚本. 执行这些脚本可以用来启动,停止,重启这些服务. 1.这些链接文件前 ...
- Vim中YouCompleteMe插件安装
背景 YouCompleteMe需要使用GCC进行编译,然而Centos 6.7默认的GCC版本太低,所以需要使用devtools-2,用来安装多个版本GCC手动编译安装GCC的坑简直不要太多(类似于 ...
- jsp相关笔记(二)
在jsp中将数据库表格内容读出为一个表格,并在表格中添加超链接: <%@ page language="java" contentType="text/html; ...