在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Leetcode[227] Basic Calculator II

2016-12-20 13:11| 发布者: zhangjf| 查看: 486| 评论: 0

摘要: LeetCode Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, /operators and empty spaces . The ...
LeetCode[227] Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, /
operators and empty spaces . The integer division should truncate
toward zero.

You may assume that the given expression is always valid.

Some examples:

  1. "3+2*2" = 7
  2. " 3/2 " = 1
  3. " 3+5 / 2 " = 5
复制代码
Stack

复杂度
O(N), O(N)

思路
用两个stack来分别记录当前的结果和操作符(operator), 注意每一次统计当前的operand的时候,要看一下下一位的操作符。如果下一位是high operator('+'或'/'), 就要先把当前的数和操作符都要先push回stack保留数据,如果当前stack不为空且已经有高位运算符在stack的顶部,就先计算一次重新计算当前的数字,再考虑之后的运算。

有一种replace all multiple spaces with one space的方法,是s.replaceAll("\s+",""), s 表示的是匹配任意的空白符,包括空格,制表符(Tab),换行符,中文全角空格等。也可以用更简单的方法,replaceAll(" +", "")。

代码

  1. public double calculator(String s) {
  2. // delete multiple spaces
  3. s = s.trim().replaceAll(" +", "");
  4. char[] arr = s.toCharArray();
  5. Stack<Double> res = new Stack<>();
  6. Stack<Character> operator = new Stack<>();
  7. res.push(0.0);
  8. operator.push('+');
  9. for(int i = 0; i < arr.length; i ++) {
  10. double val = 0;
  11. int j = i;
  12. while(j < arr.length && Character.isDigit(arr[j])) {
  13. val *= 10;
  14. val += arr[j] - '0';
  15. j ++;
  16. }
  17. //
  18. if(!operator.isEmpty() && isHighOp(operator.peek())) {
  19. double temp = getValue(res.pop(), val,operator.pop());
  20. val = temp;
  21. }
  22. if(j < arr.length && isHighOp(arr[j])) {
  23. res.push(val);
  24. operator.push(arr[j]);
  25. }
  26. else {
  27. double temp = getValue(res.pop(), val, operator.pop());
  28. res.push(temp);
  29. if(j < arr.length) operator.push(arr[j]);
  30. }
  31. i = j;
  32. }
  33. // notice the format;
  34. DecimalFormal df = new DecimalFormat("#.##");
  35. return Double.parseDouble(df.format(res.pop()));
  36. }
  37. public boolean isHighOp(Character ch) {
  38. return ch == '*' || ch == '/';
  39. }
  40. public double getValue(double op1, double op2, Character ch) {
  41. if(ch == '+') return op1 + op2;
  42. if(ch == '-') return op1 - op2;
  43. if(ch == '*') return op1 * op2;
  44. return op1 / op2;
  45. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 21:51

Copyright 2015-2025 djqfx

返回顶部