算法Sedgewick第四版-第1章基础-020一按优先级计算表达式的值
/******************************************************************************
* Compilation: javac EvaluateDeluxe.java
* Execution: java EvaluateDeluxe
* Dependencies: Stack.java
*
* Evaluates arithmetic expressions using Dijkstra's two-stack algorithm.
* Handles the following binary operators: +, -, *, / and parentheses.
*
* % echo "3 + 5 * 6 - 7 * ( 8 + 5 )" | java EvaluateDeluxe
* -58.0
*
*
* Limitiations
* --------------
* - can easily add additional operators and precedence orders, but they
* must be left associative (exponentiation is right associative)
* - assumes whitespace between operators (including parentheses)
*
* Remarks
* --------------
* - can eliminate second phase if we enclose input expression
* in parentheses (and, then, could also remove the test
* for whether the operator stack is empty in the inner while loop)
* - see http://introcs.cs.princeton.edu/java/11precedence/ for
* operator precedence in Java
*
******************************************************************************/ import java.util.TreeMap; public class EvaluateDeluxe { // result of applying binary operator op to two operands val1 and val2
public static double eval(String op, double val1, double val2) {
if (op.equals("+")) return val1 + val2;
if (op.equals("-")) return val1 - val2;
if (op.equals("/")) return val1 / val2;
if (op.equals("*")) return val1 * val2;
throw new RuntimeException("Invalid operator");
} public static void main(String[] args) { // precedence order of operators
TreeMap<String, Integer> precedence = new TreeMap<String, Integer>();
precedence.put("(", 0); // for convenience with algorithm
precedence.put(")", 0);
precedence.put("+", 1); // + and - have lower precedence than * and /
precedence.put("-", 1);
precedence.put("*", 2);
precedence.put("/", 2); Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>(); while (!StdIn.isEmpty()) { // read in next token (operator or value)
String s = StdIn.readString(); // token is a value
if (!precedence.containsKey(s)) {
vals.push(Double.parseDouble(s));
continue;
} // token is an operator
while (true) { // the last condition ensures that the operator with higher precedence is evaluated first
if (ops.isEmpty() || s.equals("(") || (precedence.get(s) > precedence.get(ops.peek()))) {
ops.push(s);
break;
} // evaluate expression
String op = ops.pop(); // but ignore left parentheses
if (op.equals("(")) {
assert s.equals(")");
break;
} // evaluate operator and two operands and push result onto value stack
else {
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
}
}
} // finished parsing string - evaluate operator and operands remaining on two stacks
while (!ops.isEmpty()) {
String op = ops.pop();
double val2 = vals.pop();
double val1 = vals.pop();
vals.push(eval(op, val1, val2));
} // last value on stack is value of expression
StdOut.println(vals.pop());
assert vals.isEmpty();
assert ops.isEmpty();
}
}
算法Sedgewick第四版-第1章基础-020一按优先级计算表达式的值的更多相关文章
- 算法Sedgewick第四版-第1章基础-001递归
		
一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)
		
一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)
		
一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)
		
一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版
		
package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)
		
一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...
 - 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)
		
一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...
 - 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的
		
1. package algorithms.stacks13; /******************************************************************* ...
 - 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法
		
1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...
 
随机推荐
- 26 python 并发编程之多进程理论
			
一 什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): egon在一个时间段内有很多任务要做:python备课的任务,写书的任 ...
 - Spring Boot 简单日志配置
			
在生产环境中,只打印error级别的错误,在测试环境中,可以调成debugapplication.properties文件## 默认使用logback logging.level.root=error ...
 - POJ - 3150 :Cellular Automaton(特殊的矩阵,降维优化)
			
A cellular automaton is a collection of cells on a grid of specified shape that evolves through a nu ...
 - jsp中引入JavaScript的方法
			
1:在页面中直接嵌入JavaScript <script language="javascript">..........</script> 2:链接外部J ...
 - source In sight 中修改自动补全快捷键方式
			
点击 “options”中的“key Assi...”,找到如下 点击“Assign New Key...”之后按键盘上的指定按键就能重新设定.
 - bzoj 1016 [JSOI2008]最小生成树计数——matrix tree(相同权值的边为阶段缩点)(码力)
			
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1016 就是缩点,每次相同权值的边构成的联通块求一下matrix tree.注意gauss里的 ...
 - 开发环境无错,部署至测试环境报错“NoSuchMethodError”OR"NoSuchClassError"
			
背景: 实现一个简单的功能,需要用到jedis的jar包连接Redis.在之前便已经有使用jedis,它的版本比较旧,是2.1的.而新实现的功能,在编码的时候使用的是2.8的.在开发环境完成单元测试后 ...
 - Rails上传文件
			
1.view <%= form_tag({:method =>"post",:controller =>"welcome",:action=& ...
 - libstdc++.so.6
			
libstdc++.so.6遇到的问题: 1.提示version `GLIBCXX_3.4.14' not found /usr/lib64/libstdc++.so.: version `GLIBC ...
 - _tprintf(), printf(),wprintf() 与控制字符 %s 和 %S(Unicoe与GB2312))
			
_tprintf() 是 printf() 和 wprintf() 的通用类型:如果定义了 _unicode,那么 _tprintf() 就会转换为 wprintf(),否则为 printf() . ...