题目
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 .
答案
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() && 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);
}
}
网友评论