您的位置:首页 > 其它

四则运算表达式

2017-05-15 00:00 477 查看
计算过程:中缀表达式->后缀表达式->计算结果

我们平时使用的标准形式的表达式就是中缀表达式

后缀表达式:不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 * ------百度百科

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;

import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Pattern;

public class StackTest {

private static Map<String, Integer> binocularOperatorPriorities = Maps.newHashMap();
private static Table<String, String, Integer> auxiliaryOperatorSorts = HashBasedTable.create();
private static Pattern pattern = Pattern.compile("-*[0-9]+");

static {
// init binocular operator
binocularOperatorPriorities.put("+", 4);
binocularOperatorPriorities.put("-", 4);
binocularOperatorPriorities.put("/", 3);
binocularOperatorPriorities.put("*", 3);

// init auxiliary operator
auxiliaryOperatorSorts.put("(", ")", 1);

}

/**
* turn infix expression to suffix expression
* O(N)
* @param infixList infix expression list
* @return suffix expression list
*/
public static List<String> infix2Suffix(List<String> infixList) {
List<String> suffixList = Lists.newArrayList();
Stack<String> operatorStack = new Stack<String>();
for (String item : infixList) {
if (pattern.matcher(item).matches()) {
suffixList.add(item);
continue;
}
pushOperator(suffixList, operatorStack, item);
}
while (!operatorStack.isEmpty()) {
suffixList.add(operatorStack.pop());
}
return suffixList;
}

private static void pushOperator(List<String> suffixStack, Stack<String> operatorStack, String waitPush) {
if (operatorStack.isEmpty()) {
operatorStack.push(waitPush);
return;
}
boolean continuePop = true;
do {
String pop = operatorStack.pop();
// discard pop and waitPush when they are a pair auxiliary operators
if (auxiliaryOperatorSorts.rowKeySet().contains(pop)
&& auxiliaryOperatorSorts.row(pop).containsKey(waitPush)) {
return;
}
if (isHigher(pop, waitPush)) {
suffixStack.add(pop);
} else {
operatorStack.push(pop);
continuePop = false;
}
} while (!operatorStack.isEmpty() && continuePop);
operatorStack.push(waitPush);
}

private static boolean isHigher(String belowOperator, String aboveOperator) {

// compare binocular and binocular
if (binocularOperatorPriorities.containsKey(belowOperator)
&& binocularOperatorPriorities.containsKey(aboveOperator)) {
return binocularOperatorPriorities.get(belowOperator) <= binocularOperatorPriorities.get(aboveOperator);
}
// compare auxiliary that at row and other
// compare other and row auxiliary that at row
// for example (( (* +(
if (auxiliaryOperatorSorts.rowKeySet().contains(belowOperator)
|| auxiliaryOperatorSorts.rowKeySet().contains(aboveOperator)) {
return false;
}
// compare other and auxiliary that at column
// for example +) *) ()
if (auxiliaryOperatorSorts.columnKeySet().contains(aboveOperator)) {
return true;
}
throw new IllegalArgumentException("输入中含有不支持的运算符");
}

/**
* calculate suffix expression
* O(N)
* @param suffixList suffix expression list
* @return result
*/
public static Integer calculate(List<String> suffixList) {
Stack<String> tempStack = new Stack<String>();
for (String item : suffixList) {
if (!binocularOperatorPriorities.containsKey(item)) {
tempStack.push(item);
continue;
}
String a = tempStack.pop();
String b = tempStack.pop();
tempStack.push(String.valueOf(cal(a, b, item)));
}
return Integer.valueOf(tempStack.pop());
}

private static Integer cal(String a, String b, String symbol) {
if ("+".equals(symbol)) {
return Integer.valueOf(a) + Integer.valueOf(b);
}
if ("-".equals(symbol)) {
return Integer.valueOf(a) - Integer.valueOf(b);
}
if ("*".equals(symbol)) {
return Integer.valueOf(a) * Integer.valueOf(b);
}
if ("/".equals(symbol)) {
return Integer.valueOf(a) / Integer.valueOf(b);
}
throw new IllegalArgumentException("不支持此运算符号:" + symbol);
}

public static void main(String[] args) {
String str = "-2 + 4 * 5 * ( ( 1 + 2 ) * 2 + 4 ) + ( 2 + 2 ) * 2";
//test : use spaces as the splitter
List<String> suffixList = infix2Suffix(Lists.newArrayList(str.split(" ")));
System.out.println(calculate(suffixList));//the result is 206
}
}

(注:没有对输入做详细的合法校验;代码中是以整数为例,可进行其他类型的拓展)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息