一、完整版的逆波兰计算器的支持
- 支持+ - * / ( )
- 支持多位数及小数
- 兼容处理,过滤任何空白字符,包括空格、制表符、换页符
1、代码如下:
package com.rf.springboot01.dataStructure.stack.reversePolishNotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;
/**
* @description: 完整版的逆波兰计算器
* 1、支持+ - * / ( )
* 2、支持多位数及小数,
* 3、兼容处理,过滤任何空白字符,包括空格、制表符、换页符
* @author: xiaozhi
* @create: 2020-07-29 22:28
*/
public class ReversePolishMultiCalc {
//匹配 + - * /运算符
public static final String SYMBOL="\\+|-|\\*|/|\\(|\\)";
public static final String LEFT="(";
public static final String RIGHT=")";
public static final String ADD="+";
public static final String SUB="-";
public static final String MUL="*";
public static final String DIV="/";
//运算符等级
public static final int LEVEL_1=1;// + - 符号等级
public static final int LEVEL_2=2;// * / 符号等级
public static final int LEVEL_HIGHT=Integer.MAX_VALUE;//括号() 符号的等级
//定义栈
static Stack stack =new Stack();
static List data= Collections.synchronizedList(new ArrayList());
//去除所有空白符
public static String replaceAllBlank(String str){
// \\s+匹配任何空白字符,包括空格、制表符、换页符等等,等价于[\f\n\r\t\v]
return str.replaceAll("\\s+","");
}
// 是否是数字 int long float double
public static boolean isNumber(String str){
//提取字符串中自定的字符
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
return pattern.matcher(str).matches();
}
//判断是不是运算符
public static boolean isSymbol(String str){
return str.matches(SYMBOL);
}
//匹配运算等级
public static int calcLevel(String str){
if("+".equals(str) || "-".equals(str)){
return LEVEL_1;
}else if("*".equals(str)|| "/".equals(str)){
return LEVEL_2;
}
return LEVEL_HIGHT;
}
//匹配
public static List doMatch (String s) throws Exception{
if(s == null || "".equals(s.trim())) throw new RuntimeException("data is empty");
if(!isNumber(s.charAt(0)+"")) throw new RuntimeException("data illeagle,start not with a number");
s = replaceAllBlank(s);
String each;
int start = 0;
for (int i = 0; i calcLevel(stack.peek())) && calcLevel(each)
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?