public class DayCode { public static void main(String[] args) { String s = "1 + 2 * 3"; int ans = new DayCode().calculate(s); System.out.println("ans is " + ans); }
/** * https://leetcode-cn.com/problems/basic-calculator-ii/ * 时间复杂度O(n) * 空间复杂度O(n) * @param s * @return */ public int calculate(String s) { Deque<Integer> stack = new ArrayDeque<>(); char preSign = '+'; int num = 0; int n = s.length(); for (int i = 0; i < n; i++) { if (Character.isDigit(s.charAt(i))) { num = num * 10 + s.charAt(i) - '0'; } if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == n - 1) { switch (preSign) { case '+': stack.push(num); break; case '-': stack.push(-num); break; case '*': stack.push(stack.pop() * num); break; case '/': stack.push(stack.pop() / num); break; default: break; } preSign = s.charAt(i); num = 0; } }
int ans = 0; while (!stack.isEmpty()) { ans += stack.pop(); } return ans; }}
评论