My code:
public class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) {
return -1;
}
Stack<Integer> st = new Stack<Integer>();
int num = 0;
char sign = '+';
for (int i = 0; i <= s.length(); i++) {
char curr = (i == s.length() ? 0 : s.charAt(i));
if (curr == ' ') {
continue;
}
else if (curr >= '0' && curr <= '9') {
num = 10 * num + (curr - '0');
}
else {
if (sign == '+') {
st.push(num);
}
else if (sign == '-') {
st.push(-num);
}
else if (sign == '*') {
st.push(st.pop() * num);
}
else {
st.push(st.pop() / num);
}
num = 0;
sign = curr;
}
}
int ret = 0;
while (!st.isEmpty()) {
ret += st.pop();
}
return ret;
}
}
reference:
https://discuss.leetcode.com/topic/42196/two-java-solutions-o-n-or-o-1-space
这道题目的做法还是比较巧妙地。
就是每个数相对应的都存一个操作符。
比如:
5 – 2 * 3
- 5
- 2
当碰到 3 时,发现操作符是 *
于是弹出 -2
-2 * 3 = -6
再入栈
5,-6
最后再把栈里面所有的数字加起来。
Anyway, Good luck, Richardo! — 09/17/2016