算法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; / ...
随机推荐
- Ajax做无刷新三级联动
1.引入JS and Jquery包 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...
- nginx负载均衡的简单实现
负载均衡是我们大流量网站要做的一个东西,下面我来给大家介绍在Nginx服务器上进行负载均衡配置方法,希望对有需要的同学有所帮助哦. 负载均衡 先来简单了解一下什么是负载均衡,单从字面上的意思来理解就可 ...
- git常用命令收藏
git init //初始化本地git环境 git clone XXX//克隆一份代码到本地仓库 git pull //把远程库的代码更新到工作台 git pull --rebase origin m ...
- 463. Island Perimeter Add to List
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represen ...
- .net core结合Consul集群&Docker实现服务治理
实战中的asp.net core结合Consul集群&Docker实现服务治理 https://www.cnblogs.com/guolianyu/p/9614050.html 0.目录 整体 ...
- Til the Cows Come Home (最短路模板题)
个人心得:模板题,不过还是找到了很多问题,真的是头痛,为什么用dijkstra算法book[1]=1就错了..... 纠结中.... Bessie is out in the field and wa ...
- 前端项目使用module.exports文件一定要Webpack编译吗?请问gulp可以编译这种文件吗
import引入类似这种文件,一定要用webpack去编译吗 module.pxports 是CMD规范的一个全局函数,功能是当前模块对外提供接口.require可以直接使用这个接口.例子: echo ...
- Linux动态gif图的录制
Linux动态gif图的录制 Linux动态gif图的录制 byzanz的安装与使用 recordmydesktop再convert成gif 参考资料 前几天写了两篇博客vim的配置和Vim的自动代码 ...
- bzoj 3771 Triple——FFT
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3771 把方案作为系数.值作为指数,两项相乘就是系数相乘.指数相加,符合意义. 考虑去重.先自 ...
- IIS:template
ylbtech-IIS: 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 5.返回顶部 6.返回顶部 7.返回顶部 8.返回顶部 9.返回顶部 10.返 ...