当前位置:   article > 正文

leetcode 224 基本计算器(只有加减和括号)

leetcode 224 基本计算器(只有加减和括号)

实现一个基本的计算器来计算一个简单的字符串表达式的值。

字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格  。

示例 1:

输入: "1 + 1"
输出: 2
示例 2:

输入: " 2-1 + 2 "
输出: 3
示例 3:

输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23

  1. class Solution {
  2. public int calculate(String s) {
  3. Stack<Integer> stack = new Stack<Integer>();
  4. // sign 代表正负
  5. int sign = 1, res = 0;
  6. int length = s.length();
  7. for (int i = 0; i < length; i++) {
  8. char ch = s.charAt(i);
  9. if (Character.isDigit(ch)) {
  10. int cur = ch - '0';
  11. //处理两位数
  12. while (i < length - 1 && Character.isDigit(s.charAt(i + 1)))
  13. cur = cur * 10 + s.charAt(++i) - '0';
  14. res = res + sign * cur;
  15. } else if (ch == '+') {
  16. sign = 1;
  17. } else if (ch == '-') {
  18. sign = -1;
  19. } else if (ch == '(') {
  20. //开始处理括号里面的
  21. stack.push(res);
  22. res = 0;
  23. stack.push(sign);
  24. sign = 1;
  25. } else if (ch == ')') {
  26. //右括号就出栈
  27. res = stack.pop() * res + stack.pop();
  28. }
  29. }
  30. return res;
  31. }
  32. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/848227
推荐阅读
相关标签
  

闽ICP备14008679号