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 .

    Example 1:

    Input: "1 + 1"
    Output: 2
    

    Example 2:

    Input: " 2-1 + 2 "
    Output: 3

    Example 3:

    Input: "(1+(4+5+2)-3)+(6+8)"
    Output: 23

    Note:

    • You may assume that the given expression is always valid.
    • Do not use the eval built-in library function.
    class Solution {
        public int calculate(String s) {
            Stack<Integer> stack = new Stack<>();
            stack.push(0);                          // Always keep most recent sum at top
            for (int i = 0, sign = 1; i < s.length(); i++) {
                if (Character.isDigit(s.charAt(i))) {
                    int num = s.charAt(i) - '0';    // Be aware of outer loop boundary and i++
                    for (; i < s.length() - 1 && Character.isDigit(s.charAt(i + 1)); i++) {
                        num = num * 10 + (s.charAt(i + 1) - '0');
                    }
                    stack.push(stack.pop() + sign * num);//pre_sum + cur_number
                } else if (s.charAt(i) == '+') {
                    sign = 1;
                } else if (s.charAt(i) == '-') {
                    sign = -1;
                } else if (s.charAt(i) == '(') {
                    stack.push(sign);//store outer_sign
                    stack.push(0);//like what we did at the start, 0 is a pre_sum
                    sign = 1;//by default sign == 1
                } else if (s.charAt(i) == ')') {    // Update last sum = current sum * sign
                    stack.push(stack.pop() * stack.pop() + stack.pop());//(local_sum * outer_sign + pre_sum)
                } /* else whitespace*/
            }
            return stack.pop();
        }
    }
  • 相关阅读:
    [USACO08OCT]Watering Hole
    [USACO08OCT]Watering Hole
    Mininet系列实验(七):Mininet脚本实现控制交换机行为
    IIS与TOMCAT协同工作---在IIS下运行JSP页面
    代码与编程题
    JAVA面试题集
    Jquery测试题
    Java---SSH(MVC)面试题
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13376229.html
Copyright © 2011-2022 走看看