題目地址:
https://www.lintcode.com/problem/basic-calculator/description
中綴表達式求值,只含加減,空格,左右小括號,和非負整數(如果不是則不以開頭)。
這個問題只是https://blog.csdn.net/qq_46105170/article/details/106310409的一個特殊情況。直接參考之即可。代碼如下:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
public class Solution {
/**
* @param s: the given expression
* @return: the result of expression
*/
public int calculate(String s) {
// Write your code here
Map<Character, Integer> prio = new HashMap<>();
prio.put('(', 1);
prio.put('+', 2);
prio.put('-', 2);
Deque<Character> ops = new ArrayDeque<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == ' ') {
continue;
}
if (ch == '(') {
ops.push('(');
} else if (ch == ')') {
while (ops.peek() != '(') {
calc(stack, ops);
}
ops.pop();
} else if (Character.isDigit(ch)) {
int j = i;
while (j < s.length() && Character.isDigit(s.charAt(j))) {
j++;
}
int num = Integer.parseInt(s.substring(i, j));
stack.push(num);
i = j - 1;
} else {
while (!ops.isEmpty() && prio.get(ops.peek()) >= prio.get(ch)) {
calc(stack, ops);
}
ops.push(ch);
}
}
while (stack.size() > 1) {
calc(stack, ops);
}
return stack.peek();
}
private void calc(Deque<Integer> stack, Deque<Character> ops) {
int n2 = stack.pop(), n1 = stack.pop();
switch (ops.pop()) {
case '+': stack.push(n1 + n2); break;
case '-': stack.push(n1 - n2); break;
}
}
}
時空複雜度。