题目
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].
答案
push numbers to number stack
push operands to operand stack
if a operand is encountered, check the priority between last operand and current operand
If last operand has higher priority(or same priority), then perform calculation with last operand first. Otherwise put current operand on top of stack, so that it's done before last operand.
To deal with parentheses:
push left paren to stack, if right paren is met, do calculations(pop stuff out of two stacks and perform calculation) until '(' is met.
class Solution {
Stack<Long> numbers = new Stack<>();
Stack<Character> ops = new Stack<>();
public int calculate(String s) {
String num = "";
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' ') continue;
if(Character.isDigit(c)) {
num = num + c;
// If no next char, or next char is not digit, then this is the number
if(i == s.length() - 1 || !Character.isDigit(s.charAt(i + 1))) {
numbers.push(Long.parseLong(num));
num = "";
}
}
else if(c == '(') {
ops.push(c);
}
else if(c == ')') {
// Keep calculating until we see (
while(ops.peek() != '(') {
char op = ops.peek();
long second = numbers.pop();
long first = numbers.pop();
operation(ops.pop(), first, second);
}
ops.pop();
}
else {
if(!ops.empty() && !isHigherPriority(c, ops.peek()) && ops.peek() != '(') {
long second = numbers.pop();
long first = numbers.pop();
operation(ops.pop(), first, second);
}
ops.push(c);
}
}
while(numbers.size() > 1) {
long second = numbers.pop();
long first = numbers.pop();
operation(ops.pop(), first, second);
}
return numbers.pop().intValue();
}
public void operation(char op, long first, long second) {
if(op == '+') numbers.push(first + second);
if(op == '-') numbers.push(first - second);
if(op == '*') numbers.push(first * second);
if(op == '/') numbers.push(first / second);
}
public boolean isHigherPriority(char op1, char op2) {
//if(op2 == '(' || op2 == ')') return false;
if((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return true;
return false;
}
}
网友评论