/******************************************************************************
* 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一按优先级计算表达式的值的更多相关文章

  1. 算法Sedgewick第四版-第1章基础-001递归

    一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...

  2. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)

    一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...

  3. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

    一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...

  4. 算法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 ...

  5. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版

    package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...

  6. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)

    一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...

  7. 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

    一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 package algorithms.elementar ...

  8. 算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

    1. package algorithms.stacks13; /******************************************************************* ...

  9. 算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

    1. package algorithms.analysis14; import algorithms.util.StdOut; import algorithms.util.StdRandom; / ...

随机推荐

  1. 求一些数字字符参数的和(Java)

    一.思路 输入数字(字符型)参数: 将字符型强制转化为整数型: 求和: 输出: 二.流程图 三.源程序代码及结果

  2. Leetcode 509. Fibonacci Number

    class Solution(object): def fib(self, N): """ :type N: int :rtype: int ""&q ...

  3. 浅学soap--------4

    引入nusoap Service.php //运行该文件,在网页中wsdl点击,可浏览生成的wsdl代码;网页提供注册的方法 <?php require_once ("nusoap/n ...

  4. PHP中不用第三个变量交换两个变量的值

    相信大家在PHP面试或者学习中经常会遇到这个问题就是“不用第三个变量来交换两个变量的值”,今天正对这个问题来讨论一下: 第一种方法:首先会想到的 这种方法简单可行,顺利的交换了两个变量的值. 第二种方 ...

  5. Gym - 100623J Just Too Lucky (数位dp)

    给定n∈[1,1e12],求1到n的所有整数中,各位数字之和能整除它本身的数的个数. 这道题与UVA-11361类似,假如设dp[u][lim][m1][m2]为枚举到第u位(从低到高数),是否受限, ...

  6. hadoop碰到的 一个问题

    在里面添加/usr/local/hadoop/etc/hadoop/log4j.properties log4j.logger.org.apache.hadoop.util.NativeCodeLoa ...

  7. 基于Python语言使用RabbitMQ消息队列(五)

    Topics 在前面教程中我们改进了日志系统,相比较于使用fanout类型交易所只能傻瓜一样地广播,我们用direct获得了选择性接收日志的能力. 虽然使用direct类型交易所改进了我们的系统,但它 ...

  8. Dynamic Web Project vs Static Web Project 以及 Project facets

    Dynamic Web Project vs Static Web Project 需要用到JSP,servlet等技术的动态服务器技术,就需要DWP:对于全部都是html页面的可以使用static ...

  9. Python collections系列之默认字典

    默认字典(defaultdict)  defaultdict是对字典的类型的补充,它默认给字典的值设置了一个类型. 1.创建默认字典 import collections dic = collecti ...

  10. 第一篇 PHP开发环境搭建以及多站点配置(基于windows 7系统)

    从今天开始,我将用PHP开发一些小的网站,大家知道LAMP(Linux)组合的优势,使PHP受到广大中小企业的喜欢.使PHP与JAVA,ASP三分天下,PHP具有跨平台性,所以在windows一样是可 ...