[算法专题] 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 基础数学算法专题
[前言] 本人学习了一定时间的算法,主要精力都花在数学类的算法上面 而数学类的算法中,本人的大部分精力也花费在了数论算法上 此类算法相对抽象,证明过程比较复杂 网络上的博客有写得非常好的,但也有写得不 ...
随机推荐
- leetcode17
回溯法,深度优先遍历(DFS) public class Solution { int[] x; int N; string DIGITS; Dictionary<char, List<s ...
- 0初识Linux
今天三八妇女节,Linux就该这么学,开课第一天.信心满满,激动,期待,要努力了.(博客为预习写的,今天又做了更新.) Linux第一印象就是黑色背景屏幕,上面还有好多代码,敲的一手好的命令操控着 ...
- java 泛型详解-绝对是对泛型方法讲解最详细的,没有之一
对java的泛型特性的了解仅限于表面的浅浅一层,直到在学习设计模式时发现有不了解的用法,才想起详细的记录一下. 本文参考java 泛型详解.Java中的泛型方法. java泛型详解 1. 概述 泛型在 ...
- LevelDB源码分析-sstable的Block
sstable中的Block(table/block.h table/block.cc table/block_builder.h table/block_builder.cc) sstable中的b ...
- javascript正则表达式中 (?=exp)、(?<=exp)、(?!exp)
(?=exp) 百度百科给的解释:非获取匹配,正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用.例如,“Windows(?=95|98|NT|2000) ...
- ppt复制文本框文字到word的方法
打开ppt按Alt+F11,插入--模块, 选中“工具”--“引用”--MicroSoft Word .. 复制代码: Sub Main() On Error Resume Next Dim tem ...
- 工具类静态方法注入dao
工具类里的一个静态方法需要调用dao查询数据库,用普通的spring注解注入一直报空指针异常,不能找到这个dao.参考的http://busing.iteye.com/blog/899322 的文章解 ...
- jar与war包区别,转自https://www.jianshu.com/p/3b5c45e8e5bd
https://www.jianshu.com/p/3b5c45e8e5bd
- Centos7下安装Docker[z]
[z]https://www.cnblogs.com/qgc1995/p/9553572.html https://yq.aliyun.com/articles/691610?spm=a2c4e.11 ...
- css3回顾 checkbox
<div class="checkBox"> <input type="checkbox" id="check1"> ...