给你一个字符串表达式 s
,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval()
。
示例 1:
示例 2:
示例 3:
1 2
| 输入:s = "(1+(4+5+2)-3)+(6+8)" 输出:23
|
此解法包含乘除,取模,幂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| class Solution { Map<Character, Integer> map = new HashMap<>(){{ put('-', 1); put('+', 1); put('*', 2); put('/', 2); put('%', 2); put('^', 3); }}; public int calculate(String s) { s = s.replaceAll(" ", ""); char[] cs = s.toCharArray(); int n = s.length(); Deque<Integer> nums = new ArrayDeque<>(); nums.addLast(0); Deque<Character> ops = new ArrayDeque<>(); for (int i = 0; i < n; i++) { char c = cs[i]; if (c == '(') { ops.addLast(c); } else if (c == ')') { while (!ops.isEmpty()) { if (ops.peekLast() != '(') { calc(nums, ops); } else { ops.pollLast(); break; } } } else { if (isNumber(c)) { int u = 0; int j = i; while (j < n && isNumber(cs[j])) u = u * 10 + (cs[j++] - '0'); nums.addLast(u); i = j - 1; } else { if (i > 0 && (cs[i - 1] == '(' || cs[i - 1] == '+' || cs[i - 1] == '-')) { nums.addLast(0); } while (!ops.isEmpty() && ops.peekLast() != '(') { char prev = ops.peekLast(); if (map.get(prev) >= map.get(c)) { calc(nums, ops); } else { break; } } ops.addLast(c); } } } while (!ops.isEmpty() && ops.peekLast() != '(') calc(nums, ops); return nums.peekLast(); } void calc(Deque<Integer> nums, Deque<Character> ops) { if (nums.isEmpty() || nums.size() < 2) return; if (ops.isEmpty()) return; int b = nums.pollLast(), a = nums.pollLast(); char op = ops.pollLast(); int ans = 0; if (op == '+') { ans = a + b; } else if (op == '-') { ans = a - b; } else if (op == '*') { ans = a * b; } else if (op == '/') { ans = a / b; } else if (op == '^') { ans = (int)Math.pow(a, b); } else if (op == '%') { ans = a % b; } nums.addLast(ans); } boolean isNumber(char c) { return Character.isDigit(c); } }
|