算法Sedgewick第四版-第1章基础-013一用stack实现自动补全表达式括号
2016-04-19 17:14
309 查看
package algorithms.exercise; import algorithms.ADT.Stack; import algorithms.util.StdIn; import algorithms.util.StdOut; /************************************************************************* * * % java Ex_1_3_09 * 1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) ) * ( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) ) * * % java Ex_1_3_09 * sqrt 1 + 2 ) ) * ( sqrt ( 1 + 2 ) ) * *************************************************************************/ public class Ex_1_3_09 { public static void main(String[] args) { Stack<String> ops = new Stack<String>(); Stack<String> vals = new Stack<String>(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("(")) ; else if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("sqrt")) ops.push(s); else if (s.equals(")")) { String op = ops.pop(); String v = vals.pop(); if (op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")) v = String.format("( %s %s %s )", vals.pop(), op, v); else if (op.equals("sqrt")) v = String.format("( %s %s )", op, v); vals.push(v); } else vals.push(s); //else vals.push(((Double)Double.parseDouble(s)).toString()); } StdOut.println(vals.pop()); } }
相关文章推荐
- Android activity组件
- 实现点击图片的放大缩小
- 根据不同条件插入不同表SQL
- 一个int数的二进制有多少个一
- 二叉树的链式存储
- dentry 和inode整理
- 让app中链接跳转跳转到淘宝店主页,如果存在淘宝app
- 传递引用的特例
- android ImageView亮度变化
- Android中的Serialable和Parcelable的区别
- CentOS7版本安装ntp服务
- EditText hint带图片的提示
- 26. Remove Duplicates from Sorted Array
- EventBus使用详解(二)——EventBus使用进阶
- andfix增量升级更新
- 绕任意轴旋转的矩阵推导
- poj 1258 Agri-Net
- java基本数据类型传递与引用传递区别详解
- shadow$_monitor_和shadow$_klass_
- UITabBarController