当前位置:   article > 正文

leetcode 计算器

leetcode 计算器
  1. class Solution {
  2. public int calculate(String s) {
  3. s = s.replaceAll(" ", "");
  4. //用一个map来存储优先级
  5. HashMap<Character, Integer> map = new HashMap<>();
  6. map.put('+', 1);
  7. map.put('-', 1);
  8. map.put('*', 2);
  9. map.put('/', 2);
  10. //用两个队列来存储,一个存储数字,一个存储字符
  11. ArrayDeque<Integer> numbers = new ArrayDeque<>();
  12. ArrayDeque<Character> fuhao = new ArrayDeque<>();
  13. //为了避免一开始就是-号,因为-会被识别成减法,所以需要一开始加一个0
  14. numbers.addLast(0);
  15. for (int i = 0; i < s.length(); i++) {
  16. char c = s.charAt(i);
  17. //如果遇到左括号,直接加入
  18. if (c == '(')
  19. fuhao.addLast(c);
  20. else if (c == ')') {
  21. //计算,就是遍历两个数组,清空符号数组,数字数组最终只保留一个数
  22. while (fuhao.getLast() != '(')
  23. cal(numbers, fuhao);
  24. fuhao.removeLast();
  25. } else if (Character.isDigit(c)) {
  26. //遍历
  27. int j = i;
  28. int num = 0;
  29. while (j < s.length() && Character.isDigit(s.charAt(j)))
  30. num = num * 10 + (int) s.charAt(j++) - (int)('0');
  31. numbers.addLast(num);
  32. //更新i,因为j此时是符号
  33. i = j - 1;
  34. } else {
  35. //此时是符号
  36. //判断是减号还是符号
  37. //如果前一个是(,那就表示是符号
  38. if (i > 0 && s.charAt(i - 1) == '(')
  39. numbers.addLast(0);
  40. //判断当前符号优先级,如果此时优先级大于最后一个优先级,则计算
  41. //如果当前是-好,上一个是*, *的优先级大于-,则直接计算,等于也直接计算
  42. while (!fuhao.isEmpty() && fuhao.getLast() != '(') {
  43. Character cur = fuhao.getLast();
  44. if (map.get(cur) < map.get(c))
  45. break;
  46. cal(numbers,fuhao);
  47. }
  48. fuhao.addLast(c);
  49. }
  50. }
  51. while (!fuhao.isEmpty()){
  52. cal(numbers,fuhao);
  53. }
  54. return numbers.getLast();
  55. }
  56. private void cal(ArrayDeque<Integer> numbers, ArrayDeque<Character> fuhao) {
  57. if (null == numbers || numbers.isEmpty() || numbers.size() < 2)
  58. return;
  59. if (null == fuhao || fuhao.isEmpty())
  60. return;
  61. Character fu = fuhao.removeLast();
  62. int b = numbers.removeLast();
  63. int a = numbers.removeLast();
  64. int result = 0;
  65. switch (fu){
  66. case '+':
  67. result = a + b;
  68. break;
  69. case '-':
  70. result = a - b;
  71. break;
  72. case '*':
  73. result = a * b;
  74. break;
  75. case '/':
  76. result = a / b;
  77. break;
  78. }
  79. numbers.addLast(result);
  80. }
  81. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号