224. Basic Calculator
Hard
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 .
Example 1:
Input: “1 + 1”
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: “(1+(4+5+2)-3)+(6+8)”
Output: 23
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
题意
含有+/-/括号和整数以及空格的表达式的解析
思路
实际上就是编译的词法分析(从字符构建整数)和语法分析(算式解析)过程。
两个栈,一个括号栈(实际上用了两个java的LinkedList,一个存储左括号的位置,另一个存储括号之前的正负号),一个数字栈,遇到右括号则进行括号内的计算。减号当作加负整数处理,加减号不存储。最后计算没有括号的算法(将数字栈中剩余的所有数字相加)。
代码
class Solution {
public int calculate(String s) {
LinkedList<Integer> numbers = new LinkedList<Integer>();
LinkedList<Integer> brackets = new LinkedList<Integer>();
LinkedList<Boolean> signBrackets = new LinkedList<Boolean>();
int num = 0, mark = 0, cnt = 0;
boolean pos = true;
for (char ch: s.toCharArray()) {
if (ch == ' ') {
continue;
} else if (ch >= '0' && ch <= '9') {
num = num * 10 + ch - '0';
} else if (ch == '(') {
brackets.add(cnt);
signBrackets.add(pos);
pos = true;
} else if (ch == '+') {
numbers.add(pos? num: -num);
num = 0;
pos = true;
++cnt;
} else if (ch == '-') {
numbers.add(pos? num: -num);
num = 0;
pos = false;
++cnt;
} else if (ch == ')') {
num = pos? num: -num;
mark = brackets.removeLast();
while (cnt-- > mark) {
num += numbers.removeLast();
}
++cnt;
pos = signBrackets.removeLast();
}
}
num = pos? num: -num;
while (!numbers.isEmpty()) {
num += numbers.removeLast();
}
return num;
}
}