zoukankan      html  css  js  c++  java
  • 224. Basic Calculator

    Implement a basic calculator to evaluate a simple expression string.

    The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

    You may assume that the given expression is always valid.

    Some examples:

    "1 + 1" = 2
    " 2-1 + 2 " = 3
    "(1+(4+5+2)-3)+(6+8)" = 23
    

    Note: Do not use the eval built-in library function.


    一般是无法顺序执行、有些数据无法处理、需要回头再来处理时用到栈。在这个计算器中,如果只有‘+’,'-'运算,可以顺序执行。碰到(),需要把括号里整个表达式算出来,因此对()要用栈来处理。

    对含有+ - * /的运算符,因为* /的优先级高于+ -,碰到了* /,前一个运算符若是+ 或者-,它需要延迟计算,因此对所有都要用到栈。

    public class Solution {
        public int calculate(String s) {
            Stack<Integer> nums = new Stack<Integer>();
            Stack<Character> ops = new Stack<Character>();
            int re = 0, num = 0;
            char op = '+';
            for (int i = 0; i < s.length(); i++) {
                switch (s.charAt(i)) {
                    case '+':
                    case '-':
                        if (op == '+') {
                            re = re + num;
                        } else {
                            re = re - num;
                        }
                        num = 0;
                        op = s.charAt(i);
                        break;
                    case '(':
                        nums.push(re);
                        ops.push(op);
                        re = 0;
                        op = '+';
                        break;
                    case ')':
                        if (op == '+') {
                            re = re + num;
                        } else {
                            re = re - num;
                        }
                        num = 0;
                        char c = ops.pop();
                        int prev = nums.pop();
                        if (c == '+') {
                            re = prev + re;
                        } else {
                            re = prev - re;
                        }
                        break;
                    case ' ':
                        break;
                    default:
                        num = 10 * num + s.charAt(i) - '0';
                }
            }
            if (num != 0) {
                if (op == '+') {
                    return re + num;
                } else {
                    return re - num;
                }
            }
            return re;
        }
    }
    
  • 相关阅读:
    内部共享上网
    Harbor部署
    一、Gitlab安装
    Dockerfile
    DockerCompose
    二、Git
    nginx域名代理
    三、jenkins持续集成工具安装
    chrome对于“submit”关键字的保留
    insightface 提取人脸特征(超简洁)
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7169496.html
Copyright © 2011-2022 走看看