赞
踩
- class Solution {
- public int calculate(String s) {
- s = s.replaceAll(" ", "");
- //用一个map来存储优先级
- HashMap<Character, Integer> map = new HashMap<>();
- map.put('+', 1);
- map.put('-', 1);
- map.put('*', 2);
- map.put('/', 2);
- //用两个队列来存储,一个存储数字,一个存储字符
- ArrayDeque<Integer> numbers = new ArrayDeque<>();
- ArrayDeque<Character> fuhao = new ArrayDeque<>();
- //为了避免一开始就是-号,因为-会被识别成减法,所以需要一开始加一个0
- numbers.addLast(0);
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- //如果遇到左括号,直接加入
- if (c == '(')
- fuhao.addLast(c);
- else if (c == ')') {
- //计算,就是遍历两个数组,清空符号数组,数字数组最终只保留一个数
- while (fuhao.getLast() != '(')
- cal(numbers, fuhao);
- fuhao.removeLast();
- } else if (Character.isDigit(c)) {
- //遍历
- int j = i;
- int num = 0;
- while (j < s.length() && Character.isDigit(s.charAt(j)))
- num = num * 10 + (int) s.charAt(j++) - (int)('0');
- numbers.addLast(num);
-
- //更新i,因为j此时是符号
- i = j - 1;
- } else {
- //此时是符号
- //判断是减号还是符号
- //如果前一个是(,那就表示是符号
- if (i > 0 && s.charAt(i - 1) == '(')
- numbers.addLast(0);
- //判断当前符号优先级,如果此时优先级大于最后一个优先级,则计算
- //如果当前是-好,上一个是*, *的优先级大于-,则直接计算,等于也直接计算
- while (!fuhao.isEmpty() && fuhao.getLast() != '(') {
- Character cur = fuhao.getLast();
- if (map.get(cur) < map.get(c))
- break;
- cal(numbers,fuhao);
- }
- fuhao.addLast(c);
- }
- }
- while (!fuhao.isEmpty()){
- cal(numbers,fuhao);
- }
- return numbers.getLast();
- }
-
- private void cal(ArrayDeque<Integer> numbers, ArrayDeque<Character> fuhao) {
- if (null == numbers || numbers.isEmpty() || numbers.size() < 2)
- return;
- if (null == fuhao || fuhao.isEmpty())
- return;
- Character fu = fuhao.removeLast();
- int b = numbers.removeLast();
- int a = numbers.removeLast();
- int result = 0;
- switch (fu){
- case '+':
- result = a + b;
- break;
- case '-':
- result = a - b;
- break;
- case '*':
- result = a * b;
- break;
- case '/':
- result = a / b;
- break;
- }
- numbers.addLast(result);
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。