给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
示例 1:
输入:s = “3+2*2”
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
提示:
1 <= s.length <= 3 * 105
s 由整数和算符 (’+’, ‘-’, ‘*’, ‘/’) 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数
//将表达式转为逆波兰表达式
class Solution {
public int calculate(String s) {
//求逆波兰表达式
Map<Character, Integer> hm = new HashMap<>();
hm.put('#', 0);
hm.put('+', 1);
hm.put('-', 1);
hm.put('*', 2);
hm.put('/', 2);
s = s.trim() + "#";
long num = 0L;
String operator = "+-*/";
List<Character> operatorStack = new ArrayList<>();
StringBuffer reversePolishNotationStr = new StringBuffer();
for(char c : s.toCharArray()) {
if(' ' == c)
continue;
if(Character.isDigit(c)) {
num = num * 10 + (c - 48);
continue;
}
reversePolishNotationStr.append(num + ",");
num = 0;
if(operator.contains(c + ""))
while(true)
if(operatorStack.isEmpty()) {
operatorStack.add(c);
break;
} else if(hm.get(c) > hm.get(operatorStack.get(operatorStack.size() - 1))) {
operatorStack.add(c);
break;
} else {
reversePolishNotationStr.append(operatorStack.get(operatorStack.size() - 1) + ",");
operatorStack.remove(operatorStack.size() - 1);
}
else
if('(' == c) {
operatorStack.add(c);
} else if(')' == c) {
boolean isExit = false;
while(true)
if('(' == operatorStack.get(operatorStack.size() - 1)) {
operatorStack.remove(operatorStack.size() - 1);
} else if(operatorStack.isEmpty()) {
isExit = true;
break;
} else {
reversePolishNotationStr.append(operatorStack.get(operatorStack.size() - 1) + ",");
operatorStack.remove(operatorStack.size() - 1);
}
if(isExit)
break;
} else {
boolean isExit = false;
while(true)
if(operatorStack.isEmpty()) {
//System.out.println("Reverse Polish Notation Done");
isExit = true;
break;
} else if('(' == operatorStack.get(operatorStack.size() - 1)) {
System.out.println("ERROR");
isExit = true;
break;
} else {
reversePolishNotationStr.append(operatorStack.get(operatorStack.size() - 1) + ",");
operatorStack.remove(operatorStack.size() - 1);
}
if(isExit)
break;
}
}
//求解表达式结果
reversePolishNotationStr = reversePolishNotationStr.deleteCharAt(reversePolishNotationStr.length() - 1);
List<Integer> stack = new ArrayList<>();
for(String ss : reversePolishNotationStr.toString().split(","))
//运算符
if(operator.contains(ss)) {
switch(ss) {
case "+": stack.add(stack.get(stack.size() - 2) + stack.get(stack.size() - 1)); break;
case "-": stack.add(stack.get(stack.size() - 2) - stack.get(stack.size() - 1)); break;
case "*": stack.add(stack.get(stack.size() - 2) * stack.get(stack.size() - 1)); break;
case "/": stack.add(stack.get(stack.size() - 2) / stack.get(stack.size() - 1)); break;
}
stack.remove(stack.size() - 2);
stack.remove(stack.size() - 2);
//数字
} else {
stack.add(Integer.valueOf(ss));
}
return Integer.valueOf(stack.get(0));
}
}